|
89367
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89367
|
|
89366
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89366
|
|
89365
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89365
|
|
89364
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89364
|
|
89363
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89363
|
|
89362
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89362
|
|
89361
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89361
|
|
89360
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89360
|
|
89359
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89359
|
|
89358
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89358
|
|
89357
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89357
|
|
89356
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89356
|
|
89355
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89355
|
|
89354
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89354
|
|
89353
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89353
|
|
89352
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89352
|
|
89351
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89351
|
|
89350
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89350
|
|
89349
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89349
|
|
89348
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89348
|
|
89347
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89347
|
|
89346
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89346
|
|
89345
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89345
|
|
89344
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89344
|
|
89343
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89343
|
|
89342
|
Last login: Wed May 27 09:47:15 on ttys011
Poetry Last login: Wed May 27 09:47:15 on ttys011
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
Poetry could not find a pyproject.toml file in /Users/lukas or its parents
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ vstg
Warning: Permanently added 'jiminny-stage-ecs1' (ED25519) to the list of known hosts.
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -ti 74532df77969 /bin/bash -c "cd /home/jiminny && bash"
root@ip-10-30-135-89:/home/jiminny# php artisan about
Environment [PASSWORD_DOTS]
Application Name [PASSWORD_DOTS] Jiminny Web App
Laravel Version [PASSWORD_DOTS] 12.58.0
PHP Version [PASSWORD_DOTS] 8.5.5
Composer Version [PASSWORD_DOTS] -
Environment [PASSWORD_DOTS] staging
Debug Mode [PASSWORD_DOTS] OFF
URL [PASSWORD_DOTS] app.staging.jiminny.com
Maintenance Mode [PASSWORD_DOTS] OFF
Timezone [PASSWORD_DOTS] UTC
Locale [PASSWORD_DOTS] en_US
Cache [PASSWORD_DOTS]
Config [PASSWORD_DOTS] CACHED
Events [PASSWORD_DOTS] NOT CACHED
Routes [PASSWORD_DOTS] CACHED
Views [PASSWORD_DOTS] CACHED
Drivers [PASSWORD_DOTS]
Broadcasting [PASSWORD_DOTS] pusher
Cache [PASSWORD_DOTS] redis
Database [PASSWORD_DOTS] mysql
Logs [PASSWORD_DOTS] errorlog
Mail [PASSWORD_DOTS] ses
Queue [PASSWORD_DOTS] sqs
Session [PASSWORD_DOTS] redis
Storage [PASSWORD_DOTS]
public/storage [PASSWORD_DOTS] NOT LINKED
Sentry [PASSWORD_DOTS]
Enabled [PASSWORD_DOTS] YES
Environment [PASSWORD_DOTS] staging
Laravel SDK Version [PASSWORD_DOTS] 4.13.0
PHP SDK Version [PASSWORD_DOTS] 4.13.0
Release [PASSWORD_DOTS] 893709
Sample Rate Errors [PASSWORD_DOTS] 100%
Sample Rate Performance Monitoring [PASSWORD_DOTS] NOT SET
Sample Rate Profiling [PASSWORD_DOTS] NOT SET
Send Default PII [PASSWORD_DOTS] DISABLED
root@ip-10-30-135-89:/home/jiminny# php artisan tinker
Psy Shell v0.12.22 (PHP 8.5.5 — cli) by Justin Hileman
New PHP manual is available (latest: 3.0.7). Update with `doc --update-manual`
> $c = \Cache::get(config('jiminny.google_text_relay_topic'));
= "358684"
> exit
INFO Goodbye.
root@ip-10-30-135-89:/home/jiminny# exit
exit
[ec2-user@ip-10-30-140-255 ~]$ exit
logout
Connection to jiminny-stage-ecs1 closed.
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
An error occurred (AccessDenied) when calling the AssumeRole operation: MultiFactorAuthentication failed with invalid MFA one time pass code.
nc: missing hostname and port
usage: nc [-46AacCDdEFhklMnOortUuvz] [-K tc] [-b boundif] [-i interval] [-p source_port]
[--apple-recv-anyif] [--apple-awdl-unres]
[--apple-boundif ifbound]
[--apple-no-cellular] [--apple-no-expensive]
[--apple-no-flowadv] [--apple-tcp-timeout conntimo]
[--apple-tcp-keepalive keepidle] [--apple-tcp-keepintvl keepintvl]
[--apple-tcp-keepcnt keepcnt] [--apple-tclass tclass]
[--tcp-adp-rtimo num_probes] [--apple-intcoproc-allow]
[--apple-tcp-adp-wtimo num_probes]
[--setsockopt-later] [--apple-no-connectx]
[--apple-delegate-pid pid] [--apple-delegate-uuid uuid]
[--apple-kao] [--apple-ext-bk-idle]
[--apple-netsvctype svc] [---apple-nowakefromsleep]
[--apple-notify-ack] [--apple-sockev]
[--apple-tos tos] [--apple-tos-cmsg]
[-s source_ip_address] [-w timeout] [-X proxy_version]
[-x proxy_address[:port]] [hostname] [port[s]]
Connection closed by UNKNOWN port 65535
lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~ $ veu
Enter MFA code for arn:aws:iam::438740370364:mfa/[EMAIL]:
Warning: Permanently added 'jiminny-eu-ecs1' (ED25519) to the list of known hosts.
A newer release of "Amazon Linux" is available.
Version 2023.10.20260330:
Version 2023.11.20260406:
Version 2023.11.20260413:
Version 2023.11.20260427:
Version 2023.11.20260505:
Version 2023.11.20260509:
Version 2023.11.20260511:
Version 2023.11.20260514:
Version 2023.11.20260526:
Run "/usr/bin/dnf check-release-update" for full release and version update info
, #_
~\_ ####_
~~ \_#####\
~~ \###|
~~ \#/ ___ Amazon Linux 2023 (ECS Optimized)
~~ V~' '->
~~~ /
~~._. _/
_/ _/
_/m/'
For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name=ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"
root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage before starting command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryPeakBeforeCommandInMb":118.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity for Cognitive Credit
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591,"provider":"hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generating access token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Syncing opportunity 494058190045...
[2026-05-28 16:20:08] production.INFO: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
Synced Centiva Capital - EU HY/IG to 7601423
[2026-05-28 16:20:08] production.INFO: Jiminny\Console\Commands\Command::run Memory usage for command {"command":"crm:sync-opportunity","memoryBeforeCommandInMb":118.0,"memoryAfterCommandInMB":126.0,"memoryPeakBeforeCommandInMb":118.0,"memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}
root@170a323e43a4:/home/jiminny#
DOCKER
Close Tab
DEV (-zsh)
Close Tab
-zsh
Close Tab
screenpipe"
Close Tab
-zsh
Close Tab
ec2-user@ip-10-30-129-190:~ (-zsh)
Close Tab
ec2-user@ip-10-20-31-146:~ (nc)
Close Tab
⌥⌘1
ec2-user@ip-10-20-31-146:~...
|
iTerm2
|
ec2-user@ip-10-20-31-146:~
|
NULL
|
89342
|
|
89341
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89341
|
|
89340
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89340
|
|
89339
|
Search
SELECT o.id, o.crm_provider_id, o.is_won, o Search
SELECT o.id, o.crm_provider_id, o.is_won, o.is_clo...
SELECT * FROM team_features where team_id = 1; SEL...
Customize
Statements...
|
PhpStorm
|
|
NULL
|
89339
|
|
89338
|
Search
PhpStormViewCoocWindowFV faVsco.|s ~#12121 Search
PhpStormViewCoocWindowFV faVsco.|s ~#12121 on JY-20963-fx-lCSamcetesconDeleteObjectsTrait.phgcomposer.isonUmacurayscrict.on© RecordSelector.phgC) Team.phdcomposer lockdependency-checker.sondew.isorhuswswo..noocea.cokecontoensyncstocc.mImportBatch.lobTrait.ohdE ids.txinieraison distx52/6Tл Y:MNnERNAuwErhoesatema20.11.25 Kovalktrait OpportunitySyncTraitliminny storaadMalicancac.m18.11.25 KovalkMMakere* Prepare associated entitles for opportunities with optimized batch processing* Returns structured data with cri 10 to DB 1D mappings for each opportunity© package-lock.json=phpstan.neon.distF phpstan-baseline.neo.<>phpunit.xmltraw_sqLquery.saMAPEAOMS maBUsege21.04.26 Nikolov210426 Nikolmprivate function prepareAssoclatedentitles(383array ScompanyAssociations21.04.26 Nikolov21042R Nikolmarray ScontactAssociations21042R Nikolm389386array &Stinings = 00 sonar-proiect propertiesEtest.pvD: array 10181125 Kouafk// Step 1: Collect all unique company and contact IDs fron associationswon tieo Oaotom.xml18.11.25 KovalRSallConpanyIds = Sthis->flattenAssociationIds(ScompanyAssociations):ssvetur.confia.i18.11.25 KovalRSallContactide = CrhicosflattanAccocfatfonTde/Scontact/eeocfatfonenM:.WEBHOOK_FILTERING_IMPLEMENTAT18.11.25 Kovaliik> 1h Extemnal Libraries18.11.25 Kovalkv #Scratches and Consoles18.11.25 Kovalikv @ Database Consoles18.11.25 KovalkStep 2: Batch sync nissing entities and get CRM ID to DB ID mappingsScompanyIdMappings = 0:ScontactIdMappings = 0:MUAO NIKOWVAEUconsole lEuDaccoun-0%ScontactsMs = 0:A DEAL RISKS (EU)704.26 NikoIOv18.11.25 Kovalt18.11.25 Kovaltit Cofemte(Shl v Accept Fle x-X Reject File ox ( 2 of 2 files →DNIEUAFUIFIN210426 NikSstart a oicrot melt as ticgervicosta outoutul liminnv coportunities1h fiminny staces1n Resu* 341h Result 50yMbatahaed500QBeAV AEUconsoleisiii users 1 s 548 msvA liminny@localhostAHSJlocalB crn provider10is wonmus closedAPROD#consoleV ASTAGINGAD stage idMistage con providen idlumorobabit.ityconsoleDockerstage_updated_atupdated at18croatcdl.atBrenotely_created.atateaniciCANEAlO ISTNL CSISAT GHMICAGE WHEM AIEA TETANG CANGINIERIG NITITT CAMAIGIAN 122 minitoe aaл=custom.log=laravellogHS_Jocal (jiminny(@localhost)e console (PROD)A console (EU):CoosolA ISTAGING1756= 1760 30-124=1763- 176)112k1#1767E1768176917701773=[CREDIT_CARD]—177)17751779iid users (EU"do minny031 49 A31 У 3 У 113 A VSELECT id. crn_provider id. is won. is_closed, stage-uodated_at. updated_at(stage_updated_atuodated.at) as stage_was.reason_for_updateFROM opportunitiesWHERE tean_id = 555 AND stage_id = 28616 AND is_wOn = ® AND deleted_at IS NULLopnsp By undated at pEscSaleiaiodr Oneon nrouiderJoros mon Oris Ginsenr nuStade 10rTkssheon nroulderous shase conu orousder al snrahantd tyo.teen topeatectt, orupetet at, o.createdLat, o.renota y- oreated.LaFROM opportunities oJOIN stages s 1.nc->1: ON s.id = o.stage_1dJOIN con_configurations cc 1.nc->1: ON cc.id = s.crn_configuration_icNHERE cC.provider =SAMOdStatement.AMOdAND dAMOSELECT o.id, o.crm_provider_jd, o.is_won, o.is_clo...SELECT • FROM tcam foaturcs whore toam id n 1: SELGuctomiatORDER BYselect * fron stages where tean_id = 416.#14267. 14269. 14283. 14293. 14294. 14296select * fron opportunities where id = 7989974:select * fron stages where id = 14269Thu 28 May 21:17:44ServiceTesteworehsermiehalsorce oelcdonkttoooeoooguni+0.Sproperties = Screbata["properties'] - this is sobject-getProperties() from the SDK. For the HubSpot batch API, getfroberties returns arrayestring, string» where dealstace value is tne raw stage ID StringAt this point l've exhausted code analysis. The only definitive way to confirm is to add a temporary log. Add this to buildoaOpportunitySyne rait.pho:1001-1008scioscostanes = sthis-sne closediea, StagesorSiswon = in_ array(Sproperties ["dealstage'], sclosedStages [*won']):Add a log hereSthis=looger=>debua Hubspot buitduoportunitybata closed stages check→ Spropertiest"dealstage'] 77 nult,*won stages' a SclosedStages [*won']," won → siskon"tean" = sthis->tean->getId).This wi immedistely show whether torooerttesf"deniatnne"1 matches whatss in wontil. Without that lon, we can'.definitively say what HubSpot is returning for these specific dealsHowever - stepping back - there is one more hypothesis I haven't checked. The epp_probability = 100 on the opportunitytcord come, tom hsocaltadcuoroodoty.Inuoscotteuurnsaroralstoneproob.tkymcanins 100% wonthwwwottonrohahtility 1a0onthaooodtur.win.racolwihas Prohobiltytt te.wonteohttm ndditm danictanAccept allalso l noticed that when running single opportunity sync it was synced property+Code$ Adaotive• •CSVvW Wiwleur Toome126040UITG.8/cnod...
|
PhpStorm
|
|
NULL
|
89338
|
|
89337
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
PhpStormViewNeweNNCCoocKelucioWindowFV faVsco.s ~#12121 on JY-20963-fx-inCSamviceTestonDeleteObjectsTrait.phgcomposer.isonUmacurayscrict.onaeeeemwwuecorolo.oruorcoaiuocrd.pnt© RecordSelector.phgC) Team.phdcomposer lockdependency-checker.sondew.isorhuswswo..noocea.cokecontoensyncstocc.mImportBatch.lobTrait.ohdE ids.txinieraison distx52/6Tл Y:MNIERNALWE.HO0Satema20.11.25 Kovalktrait OpportunitySyncTraitliminny storaadMalicancac.m18.11.25 KovalkMMakere* Prepare associated entitles for opportunities with optimized batch processing* Returns structured data with cri 10 to DB 1D mappings for each opportunity© package-lock.json=phpstan.neon.distF phpstan-baseline.neo.<>phpunit.xmltraw_sqLquery.saMAPEAOMS maBUsege21.04.26 Nikolov210426 Nikolmprivate function prepareAssoclatedentitles(383array ScompanyAssociations21.04.26 Nikolov21042R Nikolmarray ScontactAssociations,array &Stinings = 021042R Nikolm0 sonar-proiect propertiesEtest.pv386D: array 10181125 Kouafk// Step 1: Collect all unique company and contact IDs fron associationsSUn tieo Dnciom.xmi18.11.25 KovalRSallConpanyIds = Sthis->flattenAssociationIds(ScompanyAssociations):isvetur.confia.i18.11.25 KovalikSallContactide = GthicosflattanAceeocfatfonTde/Scontact/eeocfatfone)•M:.WEBHOOK_FILTERING_IMPLEMENTAT18.11.25 Kovaliik> 1h Extemnal Libraries18.11.25 Kovalikv #Scratches and Consoles18.11.25 Kovalikv @ Database Consoles18.11.25 KovalkStep 2: Batch sync nissing entities and get CRM ID to DB ID mappingsScompanyIdMappings = 0:ScontactIdMappings = 0:V AEUMUAO NIKOWDaccoun-0%ScontactsMs = 0:console lEuA DEAL RISKS (EU)704.26 NikoIOv18.11.25 Kovalt18.11.25 Kovaltit Cofemte(Shli v Accept Fle xeDNTEUAFUIFIN210426 NiKSstart a otcrot melt as tiosgervicosta outoutul liminnv coportunities1h fiminny staces18 Recult 34m fiminnw.crm.conficurations xTx.|0yMbatahaednw 1rowv00÷c6Tre Aen1EAdV AEUconsole luiii users 1 s 548 msvA liminny@localhostAHS locallinisertinos"onnontunity svne pentod"."z-" "oopontunity svne stesteoies":(=webhookBatch"1}APROD#consoleV ASTAGINGconsoleDockerCANEAlO ISTNL CSISAT GHMICAGE WHEM AIEA TETANG CANGINIERIG NITITT CAMAIGIAN 122 minitoe aaл=custom.log=laravellogHSJocal (jiminny(@localhost)e console (PROD)A console (EU) Xiid users (EU"CoosolA ISTAGINGdo minny1750031 A9 A31 V3 Y113 ASELECT id. crn_provider id. is won. is_closed, stage-uodated_at. updated_at(stage_updated.atuodated.at) as stage_was.reason_for_updateFROM opportunitiesWHERE tean_id = SSS AND stage_id = 28616 AND is_won = 0 AND deleted_at IS NUL!opnsp By undated at pEsc- 1755= 1760 34SELECT o.id, o.crn_provider_id, o.is_won, o.is_closed, o.stage_id, 10ss.crn_provider_id AS stage_crn_provider_id, s.probability.o.stage_updated_at, o.updated_at, o.created_at, o.remotely_created_atE1763=176)sonм onnontuns thesJOIN stages s 1.nc->1: ON s.id = o.stage_1dHOTM eon confsaurattone ceTuncost: NM ce fde s.con confsounaton3a#1767# WHERE cc.provider = 'hubspotE1768MHEOE Otaan Sd = 1ACendasetCommand se176912281773=1772-1773AMd e dolated at te killlORDER BY o.updated at DESC,-177%select * fron stages where tean.id = 416.#14267. 14269. 14283. 14293. 14294. 142961779select * fron opportunities where id = 7989974:select * fron stages where id = 14269Thu 28 May 21:17:40ServiceTesteworehsermiehTlasorce Daleionkttoooeoooguni+0.Sproperties = Screbata["properties'] = this is sobject-getProperties() from the SDK. For the HubSpot batch API, getfroberties returns arrayestring, string» where dealstace value is tne raw stage ID StringAt this point l've exhausted code analysis. The only definitive way to confirm is to add a temporary log. Add this to buildoaOpportunitySwne rait, pho:1001-1008scloseostanes = Sthis-sne Closediea Stages orSiskon = in array(Sproperties ['dealstage'], SclosedStages [*won']):Add a log hereSproperties("dealstage") 27 nulz"Mon stoges" as scloseoscagest won"" won → siskon"tean" = sthis→>tean-›getIdo).This wi immedistely show whether torooerttesf"deniatnne"1 matches whatss in wontil. Without that lon, we can'.definitively say what HubSpot is returning for these specific dealsHowever - stepping back = there is one more hypothesis I haven't checked. The opp probability = 100 on the opportunitytcord come, tom hsocaltadcuoroodoty.Inuoscotteuurnsaroralstoneproob.tkymcanins 100% wonthwwwottonrohahtility 1a0onthaooodtur.win.racolwihas Prohobiltytt te.wonteohttm ndditm danictanAccept allaool noucce that wheh Tunnine sinole opportuniy syne i was syncco cropet+CodeAdhotrwe• •CSVvNU MMtuid Tosme128OX 1904 chare. & lino hronkelLTG.eAenad...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89337
|
|
89336
|
HomeDMsActivityFilesLater..•More+Slack> 0(ah]Fi HomeDMsActivityFilesLater..•More+Slack> 0(ah]FileEditViewGoHistoryJiminny ...* Starredplatform-backend-...platform-inner-teamChannels# ai-chapter# alerts# backend# bugs# confusion-clinic# donut_time# engineering# general# happy_birthday& infosec_internal_all# infra-changes# infrastructure_dev# jbu-team-info# jiminny-bg# platform-team# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...WindowHelpSearch: in:#platform-inner-teamX*à platform-inner-teamMessagesBookmarks0 Channel Overview7 RefinementsO Files< PinsP Retro Action ItemsChanges:Monday, May 4th ~• Do not requeue duplicatesjiminny/app May 4th Added by GitHubNikolay Ivanov 1:48 PMhttps://github.com/jiminny/app/pull/12041, фикс за импорта на стейджове (само при hubspot се оказа )но има още една грешка за тях, слагаме стейджове от една организация на другаи не мога да намеря никьде в кода защона еи има две организации които не могат да се изтрият заради товаVasil Vasilev 2:07 PMимаше проблем със мачването на стейджове от една организация на другазаради кеширане на pipelineldпреди горе долу 10тина дена го гледахмеNikolay Ivanov 2:07 PMтой още го иматози пьт при stageвиж ми PRVasil Vasilev 2:08 PMpipelineld бeшe default за едно 5-6 организации, и там се омазваше кешапонеже няма нито crm coniguration id, нито team id включено в кеша дето заминава в РЕДИСа, да, това е сьщотодобре де, аз защо си мисля, че фикс за тоя проблем вече замина на продNikolay Ivanov 2:10 PMMessage & platform-inner-team+100% <78 • Thu 28 May 21:17:408 10Untitled +...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89336
|
|
89335
|
Project: faVsco.js, menu
PhpStormViewNeweNNCCoocKe Project: faVsco.js, menu
PhpStormViewNeweNNCCoocKelucioWindowFV faVsco.|s ~#12121 on JY-20963-fx-inCSamviceTestonDeleteObjectsTrait.phgcomposer.isonUmacurayscrict.onaeeeemwwuecorolo.oruorcoaiuocrd.pnt© RecordSelector.phgcomposer lockdependency-checker.sondew.isorhuswswo..noocea.cokecontoensyncstocc.mImportBatch.lobTrait.ohdE ids.txinieraison distx52/6Tл Y:MNIERNALWE.HO0Satema20.11.25 Kovalktrait OpportunitySyncTraitliminny storaadMalicancac.m18.11.25 KovalkMMakere* Prepare associated entitles for opportunities with optimized batch processing* Returns structured data with cri 10 to DB 1D mappings for each opportunity© package-lock.json=phpstan.neon.distF phpstan-baseline.neo.<>phpunit.xmltraw_sqLquery.saMAPEAOMS maBUsege21.04.26 Nikolov210426 Nikolmprivate function prepareAssoclatedentitles(383array ScompanyAssociations21.04.26 Nikolov21042R Nikolmarray ScontactAssociations,array &Stinings = 021042R Nikolm0 sonar-proiect propertiesEtest.pv386D: array 10181125 Kouafk// Step 1: Collect all unique company and contact IDs fron associationswon tieo Oaotom.xml18.11.25 KovalRSallConpanyIds = Sthis->flattenAssociationIds(ScompanyAssociations):isvetur.confia.i18.11.25 KovalikSallContactide = GthicosflattanAceeocfatfonTde/Scontact/eeocfatfone)•M:.WEBHOOK_FILTERING_IMPLEMENTAT18.11.25 Kovaliik> 1h Extemnal Libraries18.11.25 Kovalikv #Scratches and Consoles18.11.25 Kovalikv @ Database Consoles18.11.25 KovalkStep 2: Batch sync nissing entities and get CRM ID to DB ID mappingsScompanyIdMappings = 0:ScontactIdMappings = 0:V AEUMUAO NIKOWDaccoun-0%ScontactsMs = 9:console lEuA DEAL RISKS (EU)70426 NikoIov18.11.25 Kovalt18.11.25 Kovaltit Cofemte(Shli v Accept Fle xeX Reject File ox ( 2 of 2 files →DNTEUAFUIFIN210426 NiKSstart a oicrot melt astiosgarvicosta outoutul liminnv coportunities1h fiminny staces18 Recult 34jiminny.crm.configurations x x |• CyMbatahaednw 1rowv00÷=6Tre Aen1EAdV AEUconsole45Gii users 1 s 548 msvA liminny@localhostAHS locallinisertinos"onnontunity svne pentod"."z-" "ooportunity svne stesteoies":("webhookBatch" 1}APROD#consoleV ASTAGINGconsoleDockerCANEAlO ISTNL CSISAT GHMICAGE WHEM AIEA TETANG CANGINIERIG NITITT CAMAIGIAN 122 minitoe aaл=custom.log=laravellogHSJocal (jiminny(@localhost)e console (PROD)A console (EU) XCoosolA ISTAGING1756= 1760 %=1763- 1264112k1E1768176917761773E1772E1776—177)17781779iid users (EU"do minny031 A9 A31 УЗ У113 A VSELECT id. crn_provider id. is won. is_closed, stage-uodated_at. updated_at(stage._updated.atupdated at)) as stage-was_reason_for updateFROM opportunitiesWHERE tean_id = SSS AND stage_id = 28616 AND is_won = 0 AND deleted_at IS NUL!opnsp By undated at pEscSELECT o.id, o.crn_provider_id, o.is_won, o.is_closed, o.stage_id, 4ss.crn_provider_id AS stage_crn_provider_id, s.probability,o.stage_updated_at, o.updated_at, o.created_at, o.remotely_created_atsonм onnontuns thesJOIN stages s (1.n<->1: ON s.id = O.stage_iaJOIN con_configurations cc 1.nc->1: ON cc.id = s.crn_configuration_ic#RiHERE cc.provider = 'hubspot"WHERE o.tean_id = 416AND s.probability = 100AMNa fe mon = alAND o.deleted_at IS NULLAMn e doloted st te NilllORDER BY o.updated.at DESCselect * fron stages where tean.id = 416:#14267. 14269. 14283. 14293. 14294. 14296select * fron opportunities where id = 7989974:select * fron stages where id= 14269Thu 28 May 21:17:34ServiceTestworeewennetiealsorce oelcdonkttoooeoooguni+0.Sproperties = Screbata["properties'] = this is sobject-getProperties() from the SDK. For the HubSpot batch API, getfroberties returns arrayestring, string» where dealstace value is tne raw stage ID StringAt this point I've exhausted code analysis. The only definitive way to confirm is to add a temporary log. Add this to buildoaOpportunitySyne rait.pho:1001-1008scioscostanes = sthis-sne chosedbeal StagesosSiswon = in_ array(Sproperties ["dealstage'], sclosedStages [*won']):Add a log here→ Spropertiest"dealstage'] 77 nult,*won stages' a SclosedStages [*won'],"is won → Siskonr"tean" = sthis→>tean-›getIdo).This wi immedistely show whether torooerttesf"deniatnne"1 matches whatss in wontil. Without that lon, we can'rdefinitively say what HubSpot is returning for these specific dealsHowever - stepping back - there is one more hypothesis I haven't checked. The epp_probability = 100 on the opportunitytcord come, tom hsocaltadcuoroodoty.Inuoscotteuurnsaroralstoneproob.tkymcanins 100% wonthwwwottonrohahtility 1a0onthaooodtur.win.racolwihas Prohobiltytt te.wonteohttm ndditm danictanAccept allalso l noticed that when running single opportunity sync it was synced property+Code$ Adaptive• •CSVvW Windeur Toome124040UITG.8/enod...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89335
|
|
89334
|
HomeDMsActivityFilesLater..•More+Slack> 0(ah]Fi HomeDMsActivityFilesLater..•More+Slack> 0(ah]FileEditViewGoHistoryJiminny ...* Starredplatform-backend-...platform-inner-teamChannels# ai-chapter# alerts# backend# bugs# confusion-clinic# donut_time# engineering# general# happy_birthday& infosec_internal_all# infra-changes# infrastructure_dev# jbu-team-info# jiminny-bg# platform-team# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...WindowHelpSearch: in:#platform-inner-teamX*à platform-inner-teamMessagesBookmarks0 Channel Overview7 RefinementsO Files< PinsP Retro Action ItemsChanges:Monday, May 4th ~• Do not requeue duplicatesjiminny/app May 4th Added by GitHubNikolay Ivanov 1:48 PMhttps://github.com/jiminny/app/pull/12041, фикс за импорта на стейджове (само при hubspot се оказа )но има още една грешка за тях, слагаме стейджове от една организация на другаи не мога да намеря никьде в кода защона еи има две организации които не могат да се изтрият заради товаVasil Vasilev 2:07 PMимаше проблем със мачването на стейджове от една организация на другазаради кеширане на pipelineldпреди горе долу 10тина дена го гледахмеNikolay Ivanov 2:07 PMтой още го иматози пьт при stageвиж ми PRVasil Vasilev 2:08 PMpipelineld бeшe default за едно 5-6 организации, и там се омазваше кешапонеже няма нито crm coniguration id, нито team id включено в кеша дето заминава в РЕДИСа, да, това е сьщотодобре де, аз защо си мисля, че фикс за тоя проблем вече замина на продNikolay Ivanov 2:10 PMMessage & platform-inner-team+100% <78 • Thu 28 May 21:17:348 10Untitled +...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89334
|
|
89333
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89333
|
|
89332
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
HomeDMsActivityFilesLater..•More+Slack(ah]FileEditViewGoHistoryJiminny ...* Starredplatform-backend-...platform-inner-teamChannels# ai-chapter# alerts# backend# bugs# confusion-clinic# donut_time# engineering# general# happy_birthday& infosec_internal_all# infra-changes# infrastructure_dev# jbu-team-info# jiminny-bg# platform-team# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...WindowHelpSearch: in:#platform-inner-teamX*à platform-inner-teamMessagesP Channel Overview7 RefinementsQ Files* PinsBookmarksP Retro Action ItemsChanges:Monday, May 4th ~• Do not requeue duplicatesjiminny/app May 4th Added by GitHubNikolay Ivanov 1:48 PMhttps://github.com/jiminny/app/pull/12041, фикс за импорта на стейджове (само при hubspot се оказа )но има още една грешка за тях, слагаме стейджове от една организация на другаи не мога да намеря никьде в кода защона еи има две организации които не могат да се изтрият заради товаVasil Vasilev 2:07 PMимаше проблем със мачването на стейджове от една организация на другазаради кеширане на pipelineldпреди горе долу 10тина дена го гледахмеNikolay Ivanov 2:07 PMтой още го иматози пьт при stageвиж ми PRVasil Vasilev 2:08 PMpipelineld бeшe default за едно 5-6 организации, и там се омазваше кешапонеже няма нито crm coniguration id, нито team id включено в кеша дето заминава в РЕДИСа, да, това е сьщотодобре де, аз защо си мисля, че фикс за тоя проблем вече замина на продNikolay Ivanov 2:10 PMMessage & platform-inner-team+100% (8 • Thu 28 May 21:17:308 10Untitled +...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89332
|
|
89331
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
PhpStormViewNeWENNCCoocKelucioWindowFV faVsco.s ~#12121 on JY-20963-fx-inCSamviceTestonDeleteObjectsTrait.phgcomposer.isonUmacurayscrict.onaeeeemwwuecorolo.orurorcoaiuocrd.pnt© RecordSelector.phgC) Team.phdcomposer lockdependency-checker.sondew.isorhuswswo..noocea.cokecontoensyncstocc.m0ImportBatch.lobTrait.ohdE ids.txinieraison distx52/6Tл Y:MNTERNAuwErhoesatema20.11.25 Kovalktrait OpportunitySyncTraitliminny storaadMalicancac.m18.11.25 KovalkMMakere* Prepare associated entitles for opportunities with optimized batch processing* Returns structured data with cri 10 to DB 10 mappings for each opportunity© package-lock.json=phpstan.neon.distF phpstan-baseline.neo.<>phpunit.xmltraw_sqLquery.saMAPEAOMS ma21.04.26 Nikolov210426 Nikolm21.04.26 Nikolov21042R Nikolm21042R Nikolm0 sonar-proiect propertiesEtest.pv386181125 Kouafkwon tieo Oaotom.xmlssvetur.confia.iM:.WEBHOOK_FILTERING.IMPLEMENTAT> 1h Extemnal Librariesv #Scratches and Consolesv @ Database ConsolesV AEU18.11.25 KovalR181125 KouapkBUsegeprivate function prepareAssoclatedentitlesarray ScompanyAssociationsarray ScontactAssociations,array &Stinings = 0D: array 10// Step 1: Collect all unique company and contact IDs fron associationsSallConpanyIds = Sthis->flattenAssociationIds(ScompanyAssociations):SallContactide = GthicosflattanAceocfatfonTde/Scontact/eeocfatfone)•18.11.25 Kovaliik18.11.25 Kovalik18.11.25 Kovalik18.11.25 KovalkStep 2: Batch sync nissing entities and get CRM ID to DB ID mappingsScompanyIdMappings = 0:ScontactIdMappings = 0:MUAO NIKOWDaccoun-0%ScontactsMs = 0:console lEuA DEAL RISKS (EU)704.26 NikoIov18.11.25 Kovalt18.11.25 Kovaltit Cofemte(Shli v Accept Fle xeDNTEUAFU(FIN210426 NiKSstart a otcrot melt as tiosgervicosta outoutul liminnv coportunities1h fiminny staces18 Recult 34m fiminnw.crm.conficurations x Tx|=yMbatahaednw 1rowv0л÷=6TreAen1EAdV AEUiii users 1 s 548 msvA liminny@localhostAHS locallinisertinos"onnontunity svne pentod"."z-" "ooportunity svne stesteoies":("webhookBatch" 1)APROD#consoleV ASTAGINGconsoleDockerCANEAlO ISTNL CSISAT GHMICAGE WHEM AIEATETANG CANGINIERIG NITITT CAMAIGIAN 122 minitoe aaл= custom.log=laravellogA SF (jiminny@localhostHS_Jocal (jiminny(@localhost)e console (PROD)A console (EU)coosolA ISTAGING1750= 1768E1763- 176)#1767E1768176917761221=1222-1773E17761779iid users (EU"do minny031 A9 A31 УЗ У113 A VSELECT id. cra_provider id. is.won. is_closed, stage_uodated_at. updated_atl(stage._updated.atupdated at)) as stage-was_reason_for updateFROM opportunitiesWHERE tean_id = SSS AND stage_id = 28616 AND is_won = 0 AND deleted_at IS NUL!opnsp By undated at pEscsELEOT orstd, o,conuorovider id, o.is mon, o.is closed, o.stage_1d,s.crn_provider_id AS stage_crn_provider_id, s.probability,o.stage_updated_at, o.updated_at, o.created_at, o.remotely_created_atsonM onnontuns thesoJOIN stages s1.nc->1: ON s.id = o.stage_idlnTM eor conffauratsons ceuncost: NM cedde scon conffouration3nStatementsAMnodeSELECT olid. o.crm provider id. olit won. o.it clo.SELECT • FROM toam foaturcs where tcam id m 1: SEL...AMde deORDER BY o. Customizeselect * fron stages where tean_id = 416.#14267. 14269. 14283. 14293. 14294. 14296select * fron opportunities where id = 7989974:select * fron stages where id= 14269Thu 28 May 21:17:30ServiceTestworeewenneeiealsorce oelcdonkttoooeoooguni+0.Sproperties = Screbata["properties'] = this is sobject-sgetProperties() from the SDK. For the HubSpot batch API, getfroberties returns arrayestring, string» where dealstace value is tne raw stage ID StringAt this point l've exhausted code analysis. The only definitive way to confirm is to add a temporary log. Add this to buildoaOpportunitySyne rait.pho:1001-1008scioscostanes = sthis-sne closedbea StagesorSiswon = in_ array(Sproperties ["dealstage'], sclosedStages [*won']):Add a log hereSthis=looger->debua Hubspot buitdboportunitybata closed stages check→ Spropertiest"dealstage'] 77 nult,*won stages' = SclosedStages (*won*],"is won → Siskonr"tean" = sthis→>tean-›getIdo).This wi immedistely show whether torooerttesf"denistnne"1 matches whatss in wontil. Without that lon, we can'.definitively say what HubSpot is returning for these specific dealsHowever - stepping back - there is one more hypothesis I haven't checked. The opp _probability = 100 on the opportunitytcord come, tom hsocaltadcuoroodoty.Inuoscotreuurnsaroralstoneproob.tkymcanins 100% wonthwwwottonrohahtility 1a0onthaooodtur.win.racolwihasProhobiltytt te.wonteohttm ndditm danictanAccept allalso l noticed that when running single opportunity sync it was synced property+Code$ Adaptive• •CSVvW Windeur Toome124040UITG.8/enod...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89331
|
|
89330
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
PhpStormViewNeweNNCCoocKelucioWindowFV faVsco.s ~#12121 on JY-20963-fx-inCSamcetesconDeleteObjectsTrait.phgcomposer.isonUmacurayscrict.onaeeeemwwuecorolo.oruorcoaiuocrd.pnt© RecordSelector.phgC) Team.phdcomposer lockdependency-checker.sondew.isorhuswswo..noocea.cokecontoensyncstocc.mImportBatch.lobTrait.ohdE ids.txinieraison distx52/6Tл Y:MNIERNALWE.HO0Satema20.11.25 Kovalktrait OpportunitySyncTraitliminny storaadMalicancac.m18.11.25 KovalkMMakere* Prepare associated entitles for opportunities with optimized batch processing* Returns structured data with cri 10 to DB 10 mappings for each opportunity© package-lock.json=phpstan.neon.distF phpstan-baseline.neo.<>phpunit.xmltraw_sqLquery.saMAPEAOMS maBUsege21.04.26 Nikolov210426 Nikolmprivate function prepareAssoclatedentitles(383array ScompanyAssociations21.04.26 Nikolov21042R Nikolmarray ScontactAssociations,array &Stinings = 021042R Nikolm0 sonar-proiect propertiesEtest.pv386D: array 10181125 Kouafk// Step 1: Collect all unique company and contact IDs fron associationswon tieo Oaotom.xml18.11.25 KovalRSallConpanyIds = Sthis->flattenAssociationIds(ScompanyAssociations):isvetur.confia.i18.11.25 KovalikSallContactide = GthicosflattanAceeocfatfonTde/Scontact/eeocfatfone)•M:.WEBHOOK_FILTERING_IMPLEMENTAT18.11.25 Kovaliik> 1h Extemnal Libraries18.11.25 Kovalikv #Scratches and Consoles18.11.25 Kovalikv @ Database Consoles18.11.25 KovalkV AEUMUAO NIKOWStep 2: Batch sync nissing entities and get CRM ID to DB ID mappingsScompanyIdMappings = 0:ScontactIdMappings = 0:SaccountsMs = B:ScontactsMs = 0:console lEuA DEAL RISKS (EU)704.26 NikoIOv18.11.25 Kovalt18.11.25 Kovaltit Cofemte(Shli v Accept Fle xeDNTEUAFUIFIN210426 NiKSstart a oicrot melt astiosgervicosta outoutul liminnv coportunities1h fiminny staces18 Recult 34yMbatahaednw 1rowv0л÷<6Tre AennAAdV AEUiii users 1 s 548 msvA liminny@localhostAHS locallinisertinosAPROD#consoleV ASTAGINGconsoleDockerCANEAlO ISTNL CSISAT GHMICAGE WHEM AIEA TETANG CANGINIERIG NITITT CAMAIGIAN 122 minitoe aaлcuttom lon=laravellogHS_Jocal (jiminny(@localhost)e console (PROD)A console (EU) XCoosolA ISTAGING17501766E1763- 176)11765#1767E1768176912281771=1772-1773—17717751779iid users (EU"do minny031 A9 A31 УЗ У113 A VSELECT id, crn_provider id. is won. is_closed, stage_uodated_at. updated_at(stage updated.at = uodated at)) as stage-was reason_for updateFROM opportunitiesWHERE tean_id = SSS AND stage_id = 28616 AND is_won = 0 AND deleted_at IS NUL!opnEp By undateduat DESC:SELECT o.1d, o.crn_provider_id, o.is_won, o.is_closed, o.stage_1d,s.crn_provider_id AS stage_crn_provider_id, s.probability.o.stage_updated_at, o.updated_at, o.created_at, o.remotely_created_ato. tean_1csonм onnontuns thesJOIN stages s 1.nc->1: ON s.id = o.stage_1dHOTM eon conftauratione ceTuncost: NM ce fde s.con conffounatson3aWHERE cc.provider = 'hubspot"A WHEOE o toan Sd = 1kAND S.probability = 106AND o.deleted_at IS NULLAMn e doloted st te NilllORDER BY o.updated at DESC,select * fron stages where tean.id = 416.#14267. 14269. 14283. 14293. 14294. 14296select * fron opportunities where id = 7989974:select * fron stages where id = 14269TO0У L7Thu 28 May 21:17:26ServiceTestworeewennetiealsorce oelcdonktooeooonunim+0.Sproperties = Screbata["properties'] = this is sobject-getProperties() from the SDK. For the HubSpot batch API, getfroberties returns arrayestring, string» where dealstace value is tne raw stage ID StringAt this point l've exhausted code analysis. The only definitive way to confirm is to add a temporary log. Add this to buildoaOpportunitySyne rait.pho:1001-1008scioscostanes = sthis-sne chosedbeal StagesosSiswon = in_ array(Sproperties ["dealstage'], sclosedStages [*won']):Add a log hereSproperties("dealstage'] 22 nult*won stages' = SclosedStages (*won*]," won → siskon"tean" = sthis→>tean-›getIdo).This wi immedistely show whether torooerttesf"deniatnne"1 matches whatss in wontil. Without that lon, we can'.definitively say what HubSpot is returning for these specific dealsHowever - stepping back - there is one more hypothesis I haven't checked. The epp_probability = 100 on the opportunitytcord come, tom hsocaltadcuoroodoty.Inuoscotteuurnsaroralstoneproob.tkymcanins 100% wonthwwwottonrohahtility 1a0onthaooodtur.win.racolwihas Prohobiltytt te.wonteohttm ndditm danictanAccept allalso l noticed that when running single opportunity sync it was synced property+Code$ Adaotive• •CSVv18PASAUTG.8Aenod...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89330
|
|
89329
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
HomeDMsActivityFilesLater..•More+Slack> 0(ah]FileEditViewGoHistoryJiminny ...* Starredplatform-backend-...platform-inner-teamChannels# ai-chapter# alerts# backend# bugs# confusion-clinic# donut_time# engineering# general# happy_birthday& infosec_internal_all# infra-changes# infrastructure_dev# jbu-team-info# jiminny-bg# platform-team# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...WindowHelpSearch: in:#platform-inner-teamX*à platform-inner-teamMessagesBookmarks0 Channel Overview7 RefinementsO Files< PinsP Retro Action ItemsChanges:Monday, May 4th ~• Do not requeue duplicatesjiminny/app May 4th Added by GitHubNikolay Ivanov 1:48 PMhttps://github.com/jiminny/app/pull/12041, фикс за импорта на стейджове (само при hubspot се оказа )но има още една грешка за тях, слагаме стейджове от една организация на другаи не мога да намеря никьде в кода защона еи има две организации които не могат да се изтрият заради товаVasil Vasilev 2:07 PMимаше проблем със мачването на стейджове от една организация на другазаради кеширане на pipelineldпреди горе долу 10тина дена го гледахмеNikolay Ivanov 2:07 PMтой още го иматози пьт при stageвиж ми PRVasil Vasilev 2:08 PMpipelineld бeшe default за едно 5-6 организации, и там се омазваше кешапонеже няма нито crm coniguration id, нито team id включено в кеша дето заминава в РЕДИСа, да, това е сьщотодобре де, аз защо си мисля, че фикс за тоя проблем вече замина на продNikolay Ivanov 2:10 PMMessage & platform-inner-team+100% <78 • Thu 28 May 21:17:258 10Untitled +...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89329
|
|
89328
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
HomeDMsActivityFilesLater..•More+Slack> 0(ah]FileEditViewGoHistoryJiminny ...* Starredplatform-backend-...platform-inner-teamChannels# ai-chapter# alerts# backend# bugs# confusion-clinic# donut_time# engineering# general# happy_birthday& infosec_internal_all# infra-changes# infrastructure_dev# jbu-team-info# jiminny-bg# platform-team# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...WindowHelpSearch: in:#platform-inner-teamX*à platform-inner-teamMessagesBookmarks0 Channel Overview7 RefinementsO Files< PinsP Retro Action ItemsChanges:Monday, May 4th ~• Do not requeue duplicatesjiminny/app May 4th Added by GitHubNikolay Ivanov 1:48 PMhttps://github.com/jiminny/app/pull/12041, фикс за импорта на стейджове (само при hubspot се оказа )но има още една грешка за тях, слагаме стейджове от една организация на другаи не мога да намеря никьде в кода защона еи има две организации които не могат да се изтрият заради товаVasil Vasilev 2:07 PMимаше проблем със мачването на стейджове от една организация на другазаради кеширане на pipelineldпреди горе долу 10тина дена го гледахмеNikolay Ivanov 2:07 PMтой още го иматози пьт при stageвиж ми PRVasil Vasilev 2:08 PMpipelineld бeшe default за едно 5-6 организации, и там се омазваше кешапонеже няма нито crm coniguration id, нито team id включено в кеша дето заминава в РЕДИСа, да, това е сьщотодобре де, аз защо си мисля, че фикс за тоя проблем вече замина на продNikolay Ivanov 2:10 PMMessage & platform-inner-team+100% <78 • Thu 28 May 21:17:208 10Untitled +...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89328
|
|
89327
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89327
|
|
89326
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89326
|
|
89325
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
Previous Highlighted Error
HomeDMsActivityFilesLater..•More+Slack> 0(ah]FileEditViewGoHistoryJiminny ...* Starredplatform-backend-...platform-inner-teamChannels# ai-chapter# alerts# backend# bugs# confusion-clinic# donut_time# engineering# general# happy_birthday& infosec_internal_all# infra-changes# infrastructure_dev# jbu-team-info# jiminny-bg# platform-team# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...WindowHelpSearch: in:#platform-inner-teamX*à platform-inner-teamMessagesBookmarks0 Channel Overview7 RefinementsO Files< PinsP Retro Action ItemsChanges:Monday, May 4th ~• Do not requeue duplicatesjiminny/app May 4th Added by GitHubNikolay Ivanov 1:48 PMhttps://github.com/jiminny/app/pull/12041, фикс за импорта на стейджове (само при hubspot се оказа )но има още една грешка за тях, слагаме стейджове от една организация на другаи не мога да намеря никьде в кода защона еи има две организации които не могат да се изтрият заради товаVasil Vasilev 2:07 PMимаше проблем със мачването на стейджове от една организация на другазаради кеширане на pipelineldпреди горе долу 10тина дена го гледахмеNikolay Ivanov 2:07 PMтой още го иматози пьт при stageвиж ми PRVasil Vasilev 2:08 PMpipelineld бeшe default за едно 5-6 организации, и там се омазваше кешапонеже няма нито crm coniguration id, нито team id включено в кеша дето заминава в РЕДИСа, да, това е сьщотодобре де, аз защо си мисля, че фикс за тоя проблем вече замина на продNikolay Ivanov 2:10 PMMessage & platform-inner-team+100% <78 • Thu 28 May 21:17:088 10Untitled +...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89325
|
|
89324
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89324
|
|
89323
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89323
|
|
89322
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89322
|
|
89321
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89321
|
|
89320
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89320
|
|
89319
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'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
31
9
31
3
113
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89319
|
|
89318
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
cachedClosedDealStages
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
2/6
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Sync Changes
Hide This Notification
Code changed:
Hide
75
2
22
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\Crm\Profile;
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 = [];
/** @var array<string, array<string>> keyed by config id */
private array $cachedOpportunitySyncableFields = [];
/** @var array<string, mixed> keyed by configId:ownerId */
private array $cachedOwnerProfiles = [];
/** @var array<string, mixed> keyed by configId:businessProcessId */
private array $cachedRecordTypes = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$startTime = microtime(true);
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
$strategyNames = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$strategyNames[] = $strategyName;
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' . $strategyName,
['team' => $this->team->getId()]
);
$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);
}
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'strategies' => implode(',', $strategyNames),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
'duration_ms' => $durationMs,
]
);
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');
$batchStart = microtime(true);
$slowDeals = [];
// 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 {
$companyAssocStart = microtime(true);
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$companyAssocMs = (int) round((microtime(true) - $companyAssocStart) * 1000);
$contactAssocStart = microtime(true);
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$contactAssocMs = (int) round((microtime(true) - $contactAssocStart) * 1000);
$prepareStart = microtime(true);
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
$prepareTimings = [];
$associationsData = $this->prepareAssociatedEntities(
$companyAssociations,
$contactAssociations,
$prepareTimings
);
$prepareMs = (int) round((microtime(true) - $prepareStart) * 1000);
$missingCompanies = count(array_diff(
$allCompanyIds,
array_keys($associationsData['company_id_mappings'] ?? [])
));
$missingContacts = count(array_diff(
$allContactIds,
array_keys($associationsData['contact_id_mappings'] ?? [])
));
$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;
}
$loopStart = microtime(true);
foreach ($deals as $deal) {
$dealStart = microtime(true);
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();
}
$dealMs = (int) round((microtime(true) - $dealStart) * 1000);
if ($dealMs > 1000) {
$slowDeals[] = ['crmId' => $deal['id'], 'ms' => $dealMs];
}
}
$loopMs = (int) round((microtime(true) - $loopStart) * 1000);
$totalMs = (int) round((microtime(true) - $batchStart) * 1000);
$this->logger->info('[' . $this->getDisplayName() . '] importOpportunityBatch timing', [
'teamId' => $this->team->getId(),
'deal_count' => count($deals),
'total_ms' => $totalMs,
'company_assoc_api_ms' => $companyAssocMs,
'contact_assoc_api_ms' => $contactAssocMs,
'prepare_entities_ms' => $prepareMs,
'prepare_accounts_ms' => $prepareTimings['accounts_ms'],
'prepare_contacts_ms' => $prepareTimings['contacts_ms'],
'total_companies' => count($allCompanyIds),
'missing_companies' => $missingCompanies,
'total_contacts' => count($allContactIds),
'missing_contacts' => $missingContacts,
'deals_loop_ms' => $loopMs,
'avg_deal_ms' => ! empty($deals) ? (int) round($loopMs / count($deals)) : 0,
'slow_deals_count' => count($slowDeals),
'slow_deals' => array_slice($slowDeals, 0, 10),
]);
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 &$timings = []
): 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 = [];
$accountsMs = 0;
$contactsMs = 0;
if (! empty($allCompanyIds)) {
$start = microtime(true);
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
$accountsMs = (int) round((microtime(true) - $start) * 1000);
}
if (! empty($allContactIds)) {
$start = microtime(true);
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
$contactsMs = (int) round((microtime(true) - $start) * 1000);
}
$timings = [
'accounts_ms' => $accountsMs,
'contacts_ms' => $contactsMs,
];
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 (lean covering-index lookup)
$existingAccountsData = $this->crmEntityRepository
->getExistingAccountIdsMap($this->config, $companyIds);
$missingCompanyIds = array_diff($companyIds, array_keys($existingAccountsData));
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($existingAccountsData),
'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 (lean covering-index lookup)
$existingContactsData = $this->crmEntityRepository
->getExistingContactIdsMap($this->config, $contactIds);
$missingContactIds = array_diff($contactIds, array_keys($existingContactsData));
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($existingContactsData),
'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;
}
$properties = $crmData['properties'];
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = (string) $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile($ownerId);
}
$associations = $crmData['associations'] ?? [];
$accountId = $this->resolveAccountId($associations);
// Only fetch account if we need it for user_id fallback
$accountUserId = null;
if ($profile?->getUserId() === null && $accountId !== null) {
$accountUserId = $this->crmEntityRepository
->findAccountByConfigurationAndId(
$this->config,
$accountId
)?->getUserId();
}
$crmId = (string) $crmData['id'];
if (($profile?->getUserId() === null) && ($accountUserId === null)) {
$this->logger->error(
'[HubSpot] Skip import, no user_id found',
[
'id' => $crmId,
]
);
return null;
}
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity(
$crmId,
$properties,
$associations,
$accountUserId
);
}
return $this->createOpportunity(
$crmId,
$properties,
$associations,
$accountUserId,
);
}
/**
* Create new opportunity
*/
private function createOpportunity(
string $crmId,
array $properties,
array $associations,
?int $accountUserId = null
): ?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,
$accountUserId
);
$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,
?int $accountUserId = null
): 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,
$accountUserId
);
$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['account_id'])) {
return $associations['account_id'];
}
if (empty($associations)) {
return null;
}
// Fallback: use first company as account (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,
?int $accountUserId = null
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->getCachedOwnerProfile((string) $ownerId);
}
$userId = $profile?->getUserId() ?? $accountUserId;
$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' => $userId,
'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->getCachedBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function getCachedOwnerProfile(string $ownerId): ?Profile
{
$cacheKey = $this->config->getId() . ':' . $ownerId;
if (array_key_exists($cacheKey, $this->cachedOwnerProfiles)) {
return $this->cachedOwnerProfiles[$cacheKey];
}
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, $ownerId);
$this->cachedOwnerProfiles[$cacheKey] = $profile;
return $profile;
}
private function getCachedBusinessProcessRecordType(BusinessProcess $businessProcess): mixed
{
$cacheKey = $this->config->getId() . ':' . $businessProcess->getId();
if (array_key_exists($cacheKey, $this->cachedRecordTypes)) {
return $this->cachedRecordTypes[$cacheKey];
}
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
$this->cachedRecordTypes[$cacheKey] = $recordType;
return $recordType;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
$cacheKey = $this->getBusinessProcessCacheKey($pipelineId);
if (isset($this->cachedBusinessProcesses[$cacheKey])) {
return $this->cachedBusinessProcesses[$cacheKey];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$this->cachedClosedDealStages = null;
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$cacheKey] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function getBusinessProcessCacheKey(string $pipelineId): string
{
return $this->config->getId() . '_' . $pipelineId;
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $this->config->getId() . ':' . $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);
$this->cachedClosedDealStages = null;
}
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
{
$this->importOpportunityCrmFieldData(
$properties,
$this->getCachedOpportunitySyncableFields(),
$opportunityId
);
}
private function getCachedOpportunitySyncableFields(): array
{
$cacheKey = (string) $this->config->getId();
if (! isset($this->cachedOpportunitySyncableFields[$cacheKey])) {
$this->cachedOpportunitySyncableFields[$cacheKey] = $this->getOpportunitySyncableFields();
}
return $this->cachedOpportunitySyncableFields[$cacheKey];
}
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 {
return $this->performContactAttachment($opportunity, $id, $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, int $contactId, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contactId, [
'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' => $contactId,
'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(),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
Execute
Explain Plan
Browse Query History
View Parameters...
|
PhpStorm
|
faVsco.js – console [EU]
|
NULL
|
89318
|