|
45242
|
NULL
|
0
|
2026-05-14T14:26:31.422757+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768791422_m2.jpg...
|
PhpStorm
|
faVsco.js – WriteCrmTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Code changed:
Hide
Sync Changes
Hide This Notification...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
3089888231946957708
|
-6979382010130101301
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Code changed:
Hide
Sync Changes
Hide This Notification
Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15resterday at 13-10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.56 GB availabld• Inu 14 May 1/:20.3Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45238
|
NULL
|
NULL
|
NULL
|
|
45241
|
NULL
|
0
|
2026-05-14T14:26:33.286275+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768793286_m1.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.73333335,"top":0.3122222,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"bounds":{"left":0.75277776,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"15","depth":4,"bounds":{"left":0.7736111,"top":0.3122222,"width":0.02013889,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"12","depth":4,"bounds":{"left":0.79791665,"top":0.3122222,"width":0.02013889,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","depth":4,"bounds":{"left":0.26666668,"top":0.21111111,"width":0.6548611,"height":0.7888889},"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-4502170315616947179
|
9001456016336028185
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45243
|
1623
|
0
|
2026-05-14T14:26:34.528854+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768794528_m1.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% C•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :Projectv8• Thu 14 May 17:26:34Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny|Services\Crm\Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> D Api> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C181920|2122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?stringif ($activity->hasTitle()) {Stitle =Sactivity->getTitle();} elseif ($activity->hasActivityTypeO)) {$title = $activity->getActivityType()->getName();} else {$title = 'Conference Call':return $title;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.php55A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D2112122132147215216— 217-218-— 219220221222— 223|224225226— 227-228— 229_230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities19:26UTF-8Co 4 spaces...
|
NULL
|
2315866660195442686
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% C•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :Projectv8• Thu 14 May 17:26:34Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny|Services\Crm\Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> D Api> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C181920|2122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?stringif ($activity->hasTitle()) {Stitle =Sactivity->getTitle();} elseif ($activity->hasActivityTypeO)) {$title = $activity->getActivityType()->getName();} else {$title = 'Conference Call':return $title;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.php55A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D2112122132147215216— 217-218-— 219220221222— 223|224225226— 227-228— 229_230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities19:26UTF-8Co 4 spaces...
|
45241
|
NULL
|
NULL
|
NULL
|
|
45244
|
1624
|
0
|
2026-05-14T14:26:34.821161+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768794821_m2.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 May 1/-20.34Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-2886719812693988698
|
NULL
|
click
|
ocr
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 May 1/-20.34Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45245
|
1623
|
1
|
2026-05-14T14:26:37.558876+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768797558_m1.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :8• Thu 14 May 17:26:37QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny \Services\Crm \Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> Api|> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C181920|2122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?string{if ($activity->hasTitleO)) {$title = $activity->getTitle();} elseif ($activity->hasActivityTypeO) {Cascade 28 Cl$title = $activity->getActivityType()->gi} else {Command &81$title = 'Conference Call';return Stitle;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.php55A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D2112122132147215216_217-218-— 219— 220|221222— 223|224225226— 227-228— 229|_230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivitiesW Windsurf Teams21:45 (15 chars)UTF-8Co 4 spaces...
|
NULL
|
-8373771632646672656
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :8• Thu 14 May 17:26:37QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny \Services\Crm \Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> Api|> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C181920|2122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?string{if ($activity->hasTitleO)) {$title = $activity->getTitle();} elseif ($activity->hasActivityTypeO) {Cascade 28 Cl$title = $activity->getActivityType()->gi} else {Command &81$title = 'Conference Call';return Stitle;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.php55A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D2112122132147215216_217-218-— 219— 220|221222— 223|224225226— 227-228— 229|_230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivitiesW Windsurf Teams21:45 (15 chars)UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45246
|
1624
|
1
|
2026-05-14T14:26:39.632885+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768799632_m2.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 May 1/-20.34Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-2886719812693988698
|
NULL
|
click
|
ocr
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 May 1/-20.34Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45244
|
NULL
|
NULL
|
NULL
|
|
45247
|
1623
|
2
|
2026-05-14T14:26:40.853785+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768800853_m1.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.73333335,"top":0.3122222,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"bounds":{"left":0.75277776,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"15","depth":4,"bounds":{"left":0.7736111,"top":0.3122222,"width":0.02013889,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"12","depth":4,"bounds":{"left":0.79791665,"top":0.3122222,"width":0.02013889,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","depth":4,"bounds":{"left":0.26666668,"top":0.21111111,"width":0.6548611,"height":0.7888889},"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
6902378850207333842
|
9001456016336028185
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
45245
|
NULL
|
NULL
|
NULL
|
|
45248
|
1624
|
2
|
2026-05-14T14:26:41.849256+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768801849_m2.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"15","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"12","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.28224733,"top":1.0,"width":0.024268618,"height":-0.04788506},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
6902378850207333842
|
9001456016336028185
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
45244
|
NULL
|
NULL
|
NULL
|
|
45250
|
1623
|
3
|
2026-05-14T14:26:54.669803+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768814669_m1.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-4055537778172773550
|
-7123214895408493109
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% C•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :Projectv8• Thu 14 May 17:26:54Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.php X LogActivityTrait.php> D Webhook18© BatchSyncCollector.php© BatchSyncRedisService.phpPlainTextDecorateActivity.php© Accounng~/jiminny/app/app/Services/Crm/Salesforce/Service.phpRematchActivityOnCrmObjectDetach.php(© MatchActivityCrmData.php© ActivityPlaybookTrait.php© CrmHelperRepository.phpE.env© DetachActivityObject.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny|Services\Crm\Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> D Api> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C181920|2122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?string{if ($activity->hasTitle()) {Stitle =Sactivity->getTitle();} elseif ($activity->hasActivityTypeO)) {$title =Sactivity->getActivityType() ->getName();Cascade & YCommand 81} else {ExtractSurround$title ='Conference lauc':return Stitle;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.php55A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D2112122132147215216_217-218-— 2192202211222223224225226— 227-228-— 229_230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivitiesW Windsurf Teams22:48 (15 chars)UTF-8P. 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45249
|
1624
|
3
|
2026-05-14T14:26:54.691673+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768814691_m2.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
104
6
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->where('cr...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"104","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"6","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
4295881283034649230
|
-7851948309176185913
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
104
6
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->where('cr...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45251
|
1623
|
4
|
2026-05-14T14:26:57.483194+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768817483_m1.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLara PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :8• Thu 14 May 17:26:57QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.log© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© RemoteSearch.php© Service.php xT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php.env.staging18E.env© DetachActivityObject.phpv C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata80> C Migration› Pipedrive81v O Salesforce82› D Fields83> D OpportunityMatcher8485> OpportunitySyncStrategy86> D ProspectSearchStrategyv D ServiceTraits87T BatchSyncTrait.phpD FollowupActivityTrait.php& LogActivityTrait.phpT RecordManipulationsTraiT SyncFieldsTrait.php© Client.php© DecorateActivity.phpT DeleteObjectsTrait.php© FieldDefinitions.php© HandleHubspotRateLimit.phpclassService extends BaseService implementsSalesforceInterface,SalesforceBatchSyncInterface,SyncCrmEntitiesInterface,SyncCrmProfileRecordTypesInterface,ImportsBusinessProcessesInterface,RemoteEntityManipulationInterface,|FetchRelatedActivityInterface,SendSummaryToCrmInterface,MatchDomainByEmailInterface,SearchTaskInterface,LayoutManagementInterface,SettingsInterface,MatchCrmEntitiesInterface,RemoteEntityLookupInterface,Supports0bjectTypeParseInterface,RemoteNoteEntityManipulationInterface,VerifyTaskExistsInterfaceA 105 M6 ^888990919293949596© PayloadBuilder.php9798© Profile.php© QueryBuilder.php99100© QueryHandler.php101© Querylterator.php102© QueryResults.php103© Service.php104© SyncBatchRedisService.php105use ResolveCompanyNameByEmailTrait;use SyncFieldsTrait;use Delete0bjectsTrait;use RecordManipulationsTrait;use ServiceTraits\BatchSyncTrait;use FollowupActivityTrait;use LogActivityTrait;D Traits106C. Raceflient nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny08A1A3 X4 ^ V211m migrations oi212213=214215216m teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wi217218219220m features;team_feature:m opportunitie:221222m teams;2232241.id, CASEWHEN=225226— 227•228229=230idFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 and231• 232= 233 VIMaccounts wheiactivities— 234W Windsurf Teams86:39UTF-8C 4 spaces...
|
NULL
|
-2347888292645034360
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLara PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :8• Thu 14 May 17:26:57QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.log© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© RemoteSearch.php© Service.php xT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php.env.staging18E.env© DetachActivityObject.phpv C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata80> C Migration› Pipedrive81v O Salesforce82› D Fields83> D OpportunityMatcher8485> OpportunitySyncStrategy86> D ProspectSearchStrategyv D ServiceTraits87T BatchSyncTrait.phpD FollowupActivityTrait.php& LogActivityTrait.phpT RecordManipulationsTraiT SyncFieldsTrait.php© Client.php© DecorateActivity.phpT DeleteObjectsTrait.php© FieldDefinitions.php© HandleHubspotRateLimit.phpclassService extends BaseService implementsSalesforceInterface,SalesforceBatchSyncInterface,SyncCrmEntitiesInterface,SyncCrmProfileRecordTypesInterface,ImportsBusinessProcessesInterface,RemoteEntityManipulationInterface,|FetchRelatedActivityInterface,SendSummaryToCrmInterface,MatchDomainByEmailInterface,SearchTaskInterface,LayoutManagementInterface,SettingsInterface,MatchCrmEntitiesInterface,RemoteEntityLookupInterface,Supports0bjectTypeParseInterface,RemoteNoteEntityManipulationInterface,VerifyTaskExistsInterfaceA 105 M6 ^888990919293949596© PayloadBuilder.php9798© Profile.php© QueryBuilder.php99100© QueryHandler.php101© Querylterator.php102© QueryResults.php103© Service.php104© SyncBatchRedisService.php105use ResolveCompanyNameByEmailTrait;use SyncFieldsTrait;use Delete0bjectsTrait;use RecordManipulationsTrait;use ServiceTraits\BatchSyncTrait;use FollowupActivityTrait;use LogActivityTrait;D Traits106C. Raceflient nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny08A1A3 X4 ^ V211m migrations oi212213=214215216m teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wi217218219220m features;team_feature:m opportunitie:221222m teams;2232241.id, CASEWHEN=225226— 227•228229=230idFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 and231• 232= 233 VIMaccounts wheiactivities— 234W Windsurf Teams86:39UTF-8C 4 spaces...
|
45250
|
NULL
|
NULL
|
NULL
|
|
45252
|
1624
|
4
|
2026-05-14T14:27:25.148383+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768845148_m2.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
130
3
21
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->whe...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"11","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"130","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"21","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.28224733,"top":1.0,"width":0.024268618,"height":-0.04788506},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-15845258123973217
|
-7851939513083164217
|
idle
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
130
3
21
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->whe...
|
45249
|
NULL
|
NULL
|
NULL
|
|
45253
|
1623
|
5
|
2026-05-14T14:27:29.226455+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768849226_m1.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
130
3
21
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->whe...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"11","depth":4,"bounds":{"left":0.725,"top":0.3122222,"width":0.01875,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"130","depth":4,"bounds":{"left":0.74791664,"top":0.3122222,"width":0.025,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.77708334,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"21","depth":4,"bounds":{"left":0.79791665,"top":0.3122222,"width":0.02013889,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","depth":4,"bounds":{"left":0.26041666,"top":0.3077778,"width":0.7395834,"height":0.69222224},"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-15845258123973217
|
-7851939513083164217
|
idle
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
130
3
21
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->whe...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45254
|
1623
|
6
|
2026-05-14T14:27:33.331863+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768853331_m1.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7759925082980464890
|
-7195274138718106135
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% C•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest8• Thu 14 May 17:27:33* :QProject v© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© PlaybackController.php:=custom.log© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© RemoteSearch.phpService.php XT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.phpv C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata© HandleHubspotRateLimit.php<?php> MigrationA11 A130 X3 X21 ^› Pipedrive3namespace Jiminny (Services\Crm\Salesforce;v O Salesforce› D Fields> D OpportunityMatcher> OpportunitySyncStrategy> D ProspectSearchStrategyv D ServiceTraitsT BatchSyncTrait.phpD FollowupActivityTrait.php& LogActivityTrait.phpT RecordManipulationsTraiT SyncFieldsTrait.php© Client.php© DecorateActivity.phpT DeleteObjectsTrait.php© FieldDefinitions.php© PayloadBuilder.php© Profile.php© QueryBuilder.php© QueryHandler.php© Querylterator.php© QueryResults.php© Service.php© SyncBatchRedisService.phpD Traits5| useclass Service extends BaseService implementsSalesforceInterface,SalesforceBatchSyncInterface,SyncCrmEntitiesInterface,SyncCrmProfileRecordTypesInterface,ImportsBusinessProcessesInterface,RemoteEntityManipulationInterface,FetchRelatedActivityInterface,SendSummaryToCrmInterface,MatchDomainByEmailInterface,SearchTaskInterface,LayoutManagementInterface,SettingsInterface,MatchCrmEntitiesInterface,RemoteEntityLookupInterface,Supports0bjectTypeParseInterface,RemoteNoteEntityManipulationInterface,VerifyTaskExistsInterfaceuse ResolveCompanyNameByEmailTrait;C. Raceflient nhnuse SyncFieldsTrait;Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D211212— 213= — 227•228229=230231E232= 233 V— 234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivitiesW Windsurf Teams86:39UTF-8C 4 spaces...
|
45253
|
NULL
|
NULL
|
NULL
|
|
45255
|
1624
|
5
|
2026-05-14T14:27:33.344649+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768853344_m2.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7058342144550237105
|
-7195274138713862717
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterdav at 13.35Yesterday at 13:35Yesterday at 13.34Yesterdav at 13:33Yesterday at 13:32Yesterdav at 13:37Yesterday at 13:31Yesterday at 13.30Yesterdav at 13:30Yesterday at 13:29resterday at 15.4gYesterdav at 13:28Yesterday at 13:28Yesterday at 13:27Yesterdav at 13:26resterday at 13-4oYesterdav at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Voctorday at 12:22Yesterday at 13.21Yesterdav at 13:20Yesterdav at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13.17Yecterdav at 12:17Yesterdav at 13:16Yesterday at 13-10Yesterdav at 13:15Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:12Yesterday at 13.12Yesterdav at 13:12Yesterday at 13:11Yesterday at 13:10Yoctorday at 12:10Yesterdav at 13:09Yesterday at 13.09Yocterdav at 12:081Yesterdav at 13:08Yesterdav at 13:071S K:MPEG-4 movie16 KB17 KB29 Kb6 KE12 KB9 KB7 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPE0"4 movie8 KBMDSG-A movie37 KB10 KbMP2G-4 movie7 KBI8 KBMPEG-4 movieMPEG-4 movie8 K:72 KB14 KE13 K:MoECh movioMPEG-4 movieO KRI18 KB12 KBMPEG-1 movidMPEG-4 movie10 KEMPEG-4 movie16 KB MPEG-4 movie6 KB6 KB1MPEG-4 movie12 KB23 KB8 KBMDSG.A movicMPEG-4 movie6KE6 KBMPEG-4 movieMPEG-4 movie11 KB11 K:MPEG-4 movie20 kRMDEC A movid10 KBMPEG-4 movie7 KPMDEG-A movie5 KBMPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KB88 KBMPEG-4 movieMDEC.A movialMPEG-4 movieKO KRMDEG-A movie98 KBMPEG-4 movie97 KBMPEG-4 movie66 K:MPEG-A movie44 KB MPEG-4 movie93 KB78 KB50 kpMPEG-4 movieMDEG.A movio58 KB27 KBMPEG-4 movie7KP12 KBMADECA movid32 KB17 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 Mаy 1/•2/•32Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45256
|
1623
|
7
|
2026-05-14T14:27:36.805803+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768856805_m1.jpg...
|
PhpStorm
|
faVsco.js – WriteCrmTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% (C47•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :8• Thu 14 May 17:27:36QProject v© ReportController.php© AutomatedReportGenerated.php© TrackAutomatedReportGeneratedEvent.phpPlaybackController.php:= custom.log© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php xDecorateActivity.php© RemoteSearch.php© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php18v C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata19> Migration› Pipedrivev O Salesforce© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): Activity'timestamp'=>$decorator->formatStartTime(Sactivity),'type' => 'MEETING',48 м6 ^556263› D Fields64]:> D OpportunityMatcher65> OpportunitySyncStrategy66> D ProspectSearchStrategy67if ($activity->hasActivityType() && $this-›matchesCrmType($activity->getActivityType())){$engagement['activityType'] = $activity->getActivityType()->getName();v D ServiceTraits68T BatchSyncTrait.php69D FollowupActivityTrait.php70& LogActivityTrait.php71T RecordManipulationsTrai72$metadata = ['meetingOutcome' => $decorator->convertMeetingOutcome($activity),'internalMeetingNotes' => $decorator->generateDescription(Sactivity),T SyncFieldsTrait.php73];© Client.php74© DecorateActivity.phpT DeleteObjectsTrait.php7576© FieldDefinitions.php77© PayloadBuilder.php78© Profile.php79// Only if they are creating a fresh engagement should we update the times, otherwise it will causeif (! $activity->hasCrmProviderId)) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime()) {Smetadata[ 'startTime'] = $decorator->formatStartTime(Sactivity);Smetadata[ 'endTime'] = $decorator->formatEndTime(Sactivity);© QueryBuilder.php80© QueryHandler.php81$metadata['title'] = $decorator->generateTitle($activity);© Querylterator.php82© QueryResults.php83© Service.php84© SyncBatchRedisService.php85// For now, this is just a "meetingOutcome" field for somecustomers.Smetadata = array_merge(Smetadata, $this->fetchCustomFieldData(Sactivity, Field::0BJECT_TASK));D Traits86C. Raceflient nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D211—212— 213|214215216217218219220-221222223224225226= 227— 228229238231232233V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial,1 on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities81:53UTF-8Co 4 spaces...
|
NULL
|
8831533670893284684
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% (C47•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :8• Thu 14 May 17:27:36QProject v© ReportController.php© AutomatedReportGenerated.php© TrackAutomatedReportGeneratedEvent.phpPlaybackController.php:= custom.log© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php xDecorateActivity.php© RemoteSearch.php© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php18v C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata19> Migration› Pipedrivev O Salesforce© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): Activity'timestamp'=>$decorator->formatStartTime(Sactivity),'type' => 'MEETING',48 м6 ^556263› D Fields64]:> D OpportunityMatcher65> OpportunitySyncStrategy66> D ProspectSearchStrategy67if ($activity->hasActivityType() && $this-›matchesCrmType($activity->getActivityType())){$engagement['activityType'] = $activity->getActivityType()->getName();v D ServiceTraits68T BatchSyncTrait.php69D FollowupActivityTrait.php70& LogActivityTrait.php71T RecordManipulationsTrai72$metadata = ['meetingOutcome' => $decorator->convertMeetingOutcome($activity),'internalMeetingNotes' => $decorator->generateDescription(Sactivity),T SyncFieldsTrait.php73];© Client.php74© DecorateActivity.phpT DeleteObjectsTrait.php7576© FieldDefinitions.php77© PayloadBuilder.php78© Profile.php79// Only if they are creating a fresh engagement should we update the times, otherwise it will causeif (! $activity->hasCrmProviderId)) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime()) {Smetadata[ 'startTime'] = $decorator->formatStartTime(Sactivity);Smetadata[ 'endTime'] = $decorator->formatEndTime(Sactivity);© QueryBuilder.php80© QueryHandler.php81$metadata['title'] = $decorator->generateTitle($activity);© Querylterator.php82© QueryResults.php83© Service.php84© SyncBatchRedisService.php85// For now, this is just a "meetingOutcome" field for somecustomers.Smetadata = array_merge(Smetadata, $this->fetchCustomFieldData(Sactivity, Field::0BJECT_TASK));D Traits86C. Raceflient nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D211—212— 213|214215216217218219220-221222223224225226= 227— 228229238231232233V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial,1 on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities81:53UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45258
|
1624
|
6
|
2026-05-14T14:27:38.541793+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768858541_m2.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterdav at 13.35Yesterday at 13:35Yesterday at 13.34Yesterdav at 13:33Yesterday at 13:32Yesterdav at 13:37Yesterday at 13:31Yesterday at 13.30Yesterday at 13:30Yesterday at 13:29resterday at 15.4gYesterdav at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:26resterday at 13-4oYesterdav at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13:22Yesterday at 13.21Yesterdav at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13.17Yecterdav at 12:17Yesterday at 13:16Yesterday at 13-10Yesterdav at 13:15Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:12Yesterday at 13.12Yesterdav at 13:12Yesterday at 13:11Yesterday at 13:10Yoctorday at 12:10Yesterday at 13:09Yesterday at 13.09Yocterdav at 12:081Yesterday at 13:08Yesterdav at 13:071S K:MPEG-4 movie16 KBMPEG-4 movie17 KB29 Kb6 KEMPEG-4 movieMPEG-4 movie12 KB9 KBMPE0"4 movie7 K:8 KBMPEG-4 movie37 KB10 KbMP2G-4 movie7 KBMPEG-4 movie8 KBMPEG-4 movie8 K:72 KBMPEG-4 movie14 KB13 K:O KRIMPEG-4 movieMPEG-4 movie18 KB12 KBMPEG-4 movie10 KEMPEG-4 movie16 KB MPEG-4 movie6 KB6 KB1MPEG-4 movie12 KBMPEG-4 movie23 KB8 KBMPEG-4 movie6KEMPEG-4 movie6 KBMPEG-4 movie11 KB11 K:MPEG-4 movie20 KBMPEG-4 movie10 KBMPEG-4 movie7 KPMPEG-4 movie5 KBMPEG-4 movie11 KBMPEG-4 movie26 KBMPEG-4 movie111 KBMPEG-4 movie102 KB88 KBMPEG-4 movieKO KRMDEG-A movie98 KBMPEG-4 movie97 KBMPEG-4 movie66 K:MPEG-A movie44 KB MPEG-4 movie93 KB78 KB50 kpMPEG-4 movieMPEG-4 movie58 KB27 KBMPEG-4 movie7KP12 KBMPEG-4 movie32 KB17 K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network_• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mаy 1/•21•30Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-81150201417510139
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterdav at 13.35Yesterday at 13:35Yesterday at 13.34Yesterdav at 13:33Yesterday at 13:32Yesterdav at 13:37Yesterday at 13:31Yesterday at 13.30Yesterday at 13:30Yesterday at 13:29resterday at 15.4gYesterdav at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:26resterday at 13-4oYesterdav at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13:22Yesterday at 13.21Yesterdav at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13.17Yecterdav at 12:17Yesterday at 13:16Yesterday at 13-10Yesterdav at 13:15Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:12Yesterday at 13.12Yesterdav at 13:12Yesterday at 13:11Yesterday at 13:10Yoctorday at 12:10Yesterday at 13:09Yesterday at 13.09Yocterdav at 12:081Yesterday at 13:08Yesterdav at 13:071S K:MPEG-4 movie16 KBMPEG-4 movie17 KB29 Kb6 KEMPEG-4 movieMPEG-4 movie12 KB9 KBMPE0"4 movie7 K:8 KBMPEG-4 movie37 KB10 KbMP2G-4 movie7 KBMPEG-4 movie8 KBMPEG-4 movie8 K:72 KBMPEG-4 movie14 KB13 K:O KRIMPEG-4 movieMPEG-4 movie18 KB12 KBMPEG-4 movie10 KEMPEG-4 movie16 KB MPEG-4 movie6 KB6 KB1MPEG-4 movie12 KBMPEG-4 movie23 KB8 KBMPEG-4 movie6KEMPEG-4 movie6 KBMPEG-4 movie11 KB11 K:MPEG-4 movie20 KBMPEG-4 movie10 KBMPEG-4 movie7 KPMPEG-4 movie5 KBMPEG-4 movie11 KBMPEG-4 movie26 KBMPEG-4 movie111 KBMPEG-4 movie102 KB88 KBMPEG-4 movieKO KRMDEG-A movie98 KBMPEG-4 movie97 KBMPEG-4 movie66 K:MPEG-A movie44 KB MPEG-4 movie93 KB78 KB50 kpMPEG-4 movieMPEG-4 movie58 KB27 KBMPEG-4 movie7KP12 KBMPEG-4 movie32 KB17 K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network_• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mаy 1/•21•30Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45255
|
NULL
|
NULL
|
NULL
|
|
45257
|
1623
|
8
|
2026-05-14T14:27:40.143142+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768860143_m1.jpg...
|
PhpStorm
|
faVsco.js – WriteCrmTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Code changed:
Hide
Sync Changes
Hide This Notification
8
6
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Field;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Services\Crm\Hubspot\DecorateActivity;
use Jiminny\Services\Crm\Hubspot\Utils\AssociationCategoryV4;
use Jiminny\Services\Crm\Hubspot\Utils\AssociationTypeIdV4;
use SevenShores\Hubspot\Exceptions\BadRequest;
use SevenShores\Hubspot\Http\Response;
use SevenShores\Hubspot\Exceptions\HubspotException;
use Sentry;
trait WriteCrmTrait
{
private const string ACTION_CREATE = 'create';
private const string ACTION_UPDATE = 'update';
private const string ACTION_DELETE = 'delete';
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->getCrmType()) {
case Activity::TYPE_CONFERENCE:
$activity = $this->buildConferencePayload($activity);
break;
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildSoftphonePayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
break;
}
return $activity;
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function buildConferencePayload(Activity $activity): Activity
{
$decorator = $this->getDecorateActivity();
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $decorator->formatStartTime($activity),
'type' => 'MEETING',
];
if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {
$engagement['activityType'] = $activity->getActivityType()->getName();
}
$metadata = [
'meetingOutcome' => $decorator->convertMeetingOutcome($activity),
'internalMeetingNotes' => $decorator->generateDescription($activity),
];
// Only if they are creating a fresh engagement should we update the times, otherwise it will cause a cal sync.
if (! $activity->hasCrmProviderId()) {
if ($activity->hasActualStartTime() && $activity->hasActualEndTime()) {
$metadata['startTime'] = $decorator->formatStartTime($activity);
$metadata['endTime'] = $decorator->formatEndTime($activity);
}
$metadata['title'] = $decorator->generateTitle($activity);
}
// For now, this is just a "meetingOutcome" field for some customers.
$metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));
return $this->upsertActivity($activity, $engagement, $metadata);
}
private function fetchCustomFieldData(Activity $activity, string $objectType): array
{
$payload = [];
$fieldDataRepository = app(FieldDataRepository::class);
$fieldData = $fieldDataRepository->getActivityFieldData($activity, $objectType);
foreach ($fieldData as $data) {
// Add the field and value to the payload.
$payload += [
$data->getField()->getCrmProviderId() => $data->getValue(),
];
}
return $payload;
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function upsertActivity(Activity $activity, array $engagement, array $metadata): Activity
{
if (! $activity->hasCrmProviderId()) {
$this->createActivity($activity, $engagement, $metadata);
return $activity;
}
try {
$oldEngagement = $this->getClient()->getEngagementData($activity->getCrmProviderId());
} catch (HubspotException $e) {
$this->logger->warning('[HubSpot] Engagement not found', [
'activity_id' => $activity->getUuid(),
'crm_provider_id' => $activity->getCrmProviderId(),
'exception' => $e->getMessage(),
]);
// potentially here we can log new activity if it is not found
return $activity;
}
$type = $oldEngagement['engagement']['type'] ?? null;
$bodyAttribute = $activity->isTypeConference() ? 'internalMeetingNotes' : 'body';
$decorator = $this->getDecorateActivity();
if ($type !== 'TASK') {
$oldDescription = $oldEngagement['metadata'][$bodyAttribute] ?? '';
$metadata[$bodyAttribute] = $decorator->mergeDescriptions(
$metadata[$bodyAttribute],
$oldDescription
);
$oldAssociations = $oldEngagement['associations'] ?? [];
$this->updateNonTaskActivity($activity, $engagement, $metadata, $oldAssociations);
} else {
$oldTaskBody = $oldEngagement['metadata']['body'] ?? '';
$metadata[$bodyAttribute] = $decorator->mergeDescriptions(
$metadata[$bodyAttribute],
$oldTaskBody
);
$this->updateTask($activity, $engagement, $metadata);
}
return $activity;
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function updateNonTaskActivity(
Activity $activity,
array $engagement,
array $metadata,
array $oldAssociations
): void {
if ($activity->isTypeConference()) {
$this->updateMeetingV3($activity->getCrmProviderId(), $engagement, $metadata);
} else {
$this->getClient()->updateEngagement($activity->getCrmProviderId(), $engagement, $metadata);
}
$this->updateActivityAssociations($activity, $oldAssociations);
$this->logCrmEngagementManipulation(
self::ACTION_UPDATE,
['crmId' => $activity->getCrmProviderId()],
$metadata,
);
}
private function updateActivityAssociations(Activity $activity, array $oldAssociations): void
{
$currentAssociations = $this->getActivityAssociations($activity);
$associationChanges = $this->getAssociationDifferences($activity, $oldAssociations, $currentAssociations);
// No changes - exit
if (empty($associationChanges)) {
return;
}
$this->logger->info('[HubSpot] Updating associations', [
'team' => $this->team->getUuid(),
'activity' => $activity->getUuid(),
'associationChanges' => $associationChanges,
]);
$this->updateAssociations($activity, $associationChanges);
}
private function getAssociationDifferences(
Activity $activity,
array $oldAssociations,
array $currentAssociations
): array {
$objects = ['contactIds', 'companyIds', 'dealIds'];
$changes = [];
foreach ($objects as $object) {
$oldIds = $this->normalizeIds($oldAssociations[$object] ?? []);
$currentIds = $this->normalizeIds($currentAssociations[$object] ?? []);
$added = array_diff($currentIds, $oldIds);
$removed = array_diff($oldIds, $currentIds);
$type = match ($object) {
'contactIds' => 'contact',
'companyIds' => 'company',
'dealIds' => 'deal',
};
$shouldIncludeRemoved = $this->shouldIncludeRemovedAssociations($type, $added, $activity);
if (! empty($removed) && ! $shouldIncludeRemoved) {
$this->logger->info('[HubSpot] Skipping association removal', [
'team' => $this->team->getUuid(),
'type' => $type,
'oldIds' => $oldIds,
'currentIds' => $currentIds,
'skippedRemovals' => array_values($removed),
]);
}
if (! empty($added) || (! empty($removed) && $shouldIncludeRemoved)) {
$changes[$type] = [
'added' => array_values($added),
'removed' => array_values($removed),
];
}
}
return $changes;
}
/**
* Determines whether removed associations should be synced to HubSpot.
*
* For contacts and companies, we always sync removals (original behavior).
* For deals, we only sync removals when:
* - There are new deals being added (replacement scenario), OR
* - The activity has an account associated (indicating intentional association management)
*
* This prevents accidentally removing deal associations that exist in HubSpot
* but not in Jiminny's database (e.g., deals manually added by users in HubSpot).
*/
private function shouldIncludeRemovedAssociations(string $type, array $added, Activity $activity): bool
{
// Contacts and companies: always sync removals
if ($type !== 'deal') {
return true;
}
// Deals: sync removals if we're adding new deals (replacement)
if (! empty($added)) {
return true;
}
// Deals: sync removals only if activity has an account (intentional management)
return $activity->hasAccount();
}
private function normalizeIds(array $ids): array
{
$stringIds = array_map('strval', $ids);
$uniqueIds = array_unique($stringIds);
sort($uniqueIds);
return $uniqueIds;
}
private function updateAssociations(Activity $activity, array $associationChanges): void
{
$objectType = $activity->isTypeConference() ? 'meeting' : 'call';
foreach ($associationChanges as $type => $changes) {
if (! empty($changes['added'])) {
$associationType = (new AssociationTypeIdV4())->getAssociationType($objectType, $type);
$payload = $this->payloadBuilder->buildAddAssociationPayload(
$activity->getCrmProviderId(),
$changes['added'],
$associationType
);
$this->getClient()->addAssociations($objectType, $type, $payload);
}
if (! empty($changes['removed'])) {
$payload = $this->payloadBuilder->buildRemoveAssociationPayload(
$activity->getCrmProviderId(),
$changes['removed']
);
$this->getClient()->removeAssociations($objectType, $type, $payload);
}
}
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function updateMeetingV3(string $meetingId, array $engagement, array $metadata): Response
{
// If already set by us/client, do not override it
if (isset($engagement['activityType']) && $this->hasEngagementActivityType($meetingId)) {
$this->logger->info('[HubSpot] Meeting activity type already set', [
'meetingId' => $meetingId,
'activityType' => $engagement['activityType'],
]);
unset($engagement['activityType']);
}
$payload = $this->payloadBuilder->getV3MeetingPayload($engagement, $metadata);
return $this->getClient()->updateMeeting($meetingId, $payload);
}
private function hasEngagementActivityType(string $engagementId): bool
{
try {
$engagementData = $this->getClient()->getEngagementData($engagementId);
if (isset($engagementData['engagement']['activityType']) && trim($engagementData['engagement']['activityType']) != '') {
return true;
}
return false;
} catch (\Exception $exception) {
Sentry::captureException($exception);
$this->logger->info('[HubSpot] Exception checking engagement activity type, defaulting to preserve existing', [
'engagementId' => $engagementId,
'exception' => $exception->getMessage(),
]);
}
return true;
}
private function updateTask(Activity $activity, array $engagement, array $metadata): void
{
$this->getClient()->deleteEngagement($activity->getCrmProviderId());
$this->logCrmEngagementManipulation(
self::ACTION_DELETE,
['crmId' => $activity->getCrmProviderId()],
);
$this->createActivity($activity, $engagement, $metadata);
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function createActivity(Activity $activity, array $engagement, array $metadata): void
{
$associations = $this->getActivityAssociations($activity);
$associationsV4 = $this->convertActivityMeetingAssociationsV4($activity);
if ($activity->isTypeConference()) {
try {
$hsEngagement = $this->createMeetingV3($engagement, $associationsV4, $metadata);
$activityId = $hsEngagement->data->id;
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associationsV4);
$activity->crm_provider_id = $activityId;
$activity->save();
} catch (BadRequest $exception) {
Sentry::captureException($exception);
$this->logger->warning('[HubSpot] Error while creating engagements', [
'activity' => $activity->getUuid(),
'message' => $exception->getMessage(),
'engagement' => $engagement,
'associations' => $associations,
'metadata' => $metadata,
]);
}
} else {
try {
$hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);
$activityId = $hsEngagement->data->engagement->id;
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);
$activity->crm_provider_id = $activityId;
$activity->save();
} catch (BadRequest $exception) {
Sentry::captureException($exception);
$this->logger->warning('[HubSpot] Error while creating engagements', [
'activity' => $activity->getUuid(),
'message' => $exception->getMessage(),
'engagement' => $engagement,
'associations' => $associations,
'metadata' => $metadata,
]);
}
}
}
private function convertActivityMeetingAssociationsV4(Activity $activity): array
{
$associations = [];
$contactIds = $this->getParticipantsIds($activity);
foreach ($contactIds as $contactId) {
$associations[] = $this->buildAssociation(
(int) $contactId,
[AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_CONTACT]
);
}
if ($activity->hasAccount()) {
$crmProviderId = $activity->getAccount()?->getCrmProviderId();
if ($crmProviderId) {
$associations[] = $this->buildAssociation(
(int) $crmProviderId,
[AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_COMPANY]
);
}
}
if ($activity->hasOpportunity()) {
$crmProviderId = $activity->getOpportunity()?->getCrmProviderId();
if ($crmProviderId) {
$associations[] = $this->buildAssociation(
(int) $crmProviderId,
[AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_DEAL]
);
}
}
return $associations;
}
private function buildAssociation(int $id, array $categoryToTypeIds): array
{
$types = [];
foreach ($categoryToTypeIds as $category => $typeId) {
$types[] = $this->buildAssociationType($category, $typeId);
}
return [
'to' => ['id' => (string) $id],
'types' => $types,
];
}
private function buildAssociationType(string $category, int $typeId): array
{
return [
'associationCategory' => $category,
'associationTypeId' => $typeId,
];
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function createMeetingV3(array $engagement, array $associations, array $metadata): Response
{
$payload = $this->payloadBuilder->getV3MeetingPayload(
engagement: $engagement,
metadata: $metadata,
associations: $associations
);
return $this->getClient()->createMeeting($payload);
}
/**
* @throws BadRequest
* @throws HubspotException
*/
private function buildSoftphonePayload(Activity $activity): Activity
{
$decorator = $this->getDecorateActivity();
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $decorator->formatCreatedAt($activity),
'type' => 'CALL',
];
if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {
$engagement['activityType'] = $activity->getActivityType()->getName();
}
$metadata = [
'toNumber' => $decorator->formatCallToParticipant($activity),
'fromNumber' => $activity->getFromParticipant()?->getPhoneNumber(),
'status' => $decorator->convertCallStatus($activity),
'durationMilliseconds' => (int) $activity->getDuration() * 1000,
'body' => $decorator->generateDescription($activity),
];
// For now, this is just a "disposition" field to store Call Outcome.
$metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));
return $this->upsertActivity($activity, $engagement, $metadata);
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function buildTextMessagePayload(Activity $activity): Activity
{
$decorator = $this->getDecorateActivity();
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $decorator->formatCreatedAt($activity),
'type' => 'NOTE',
];
$metadata = [
'body' => $decorator->generateDescription($activity),
];
return $this->upsertActivity($activity, $engagement, $metadata);
}
private function getActivityAssociations(Activity $activity): array
{
return [
'contactIds' => $this->getParticipantsIds($activity),
'companyIds' => $activity->hasAccount() ? [$activity->getAccount()->getCrmProviderId()] : [],
'dealIds' => $activity->hasOpportunity() ? [$activity->getOpportunity()->getCrmProviderId()] : [],
'ownerIds' => [],
];
}
/**
* Get DecorateActivity instance. Can be overridden in tests for mocking.
*/
protected function getDecorateActivity(): DecorateActivity
{
return new DecorateActivity();
}
public function saveFollowupActivity(Activity $activity, array $fields): ?string
{
if (empty($fields['subject'])) {
return null;
}
$associations = $this->getActivityAssociations($activity);
if (empty($fields['timestamp']) === false) {
$formatTimestamp = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $fields['timestamp']);
$timestamp = $formatTimestamp->getTimestamp();
} else {
$timestamp = strtotime('+1 day');
}
$reminder = null;
if (empty($fields['reminder']) === false) {
$formatReminder = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $fields['reminder']);
$reminder = $formatReminder->getTimestamp() * 1000;
}
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $timestamp * 1000,
'type' => 'TASK',
];
$metadata = [
'subject' => $fields['subject'],
'body' => '',
'status' => 'NOT_STARTED',
'taskType' => 'CALL',
'reminders' => $reminder ? [$reminder] : [],
];
try {
$hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);
} catch (BadRequest $e) {
$this->logger->info('[HubSpot] Failed to create followup task', [
'activity' => $activity->getUuid(),
'engagement' => $engagement,
'metadata' => $metadata,
'error' => $e->getMessage(),
]);
return null;
}
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);
// We don't actually create a corresponding activity object on our side yet.
return (string) $hsEngagement->data->engagement->id;
}
private function logCrmEngagementManipulation(
string $action,
array $engagementData,
array $data = [],
array $associations = [],
): void {
$payload = ['team' => $this->team->getUuid()];
if ($action === self::ACTION_CREATE) {
$payload['engagementData'] = $engagementData;
$payload['data'] = $data;
$payload['associations'] = $associations;
}
if ($action === self::ACTION_UPDATE) {
$payload['engagementId'] = $engagementData['crmId'];
$payload['data'] = $data;
}
if ($action === self::ACTION_DELETE) {
$payload['engagementId'] = $engagementData['crmId'];
}
$this->logger->info('[HubSpot] Engagement manipulated (' . $action . ')', $payload);
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.78055555,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"6","depth":4,"bounds":{"left":0.80138886,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Hubspot\\Utils\\AssociationCategoryV4;\nuse Jiminny\\Services\\Crm\\Hubspot\\Utils\\AssociationTypeIdV4;\nuse SevenShores\\Hubspot\\Exceptions\\BadRequest;\nuse SevenShores\\Hubspot\\Http\\Response;\nuse SevenShores\\Hubspot\\Exceptions\\HubspotException;\nuse Sentry;\n\ntrait WriteCrmTrait\n{\n private const string ACTION_CREATE = 'create';\n private const string ACTION_UPDATE = 'update';\n private const string ACTION_DELETE = 'delete';\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->getCrmType()) {\n case Activity::TYPE_CONFERENCE:\n $activity = $this->buildConferencePayload($activity);\n\n break;\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildSoftphonePayload($activity);\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function buildConferencePayload(Activity $activity): Activity\n {\n $decorator = $this->getDecorateActivity();\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $decorator->formatStartTime($activity),\n 'type' => 'MEETING',\n ];\n\n if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {\n $engagement['activityType'] = $activity->getActivityType()->getName();\n }\n\n $metadata = [\n 'meetingOutcome' => $decorator->convertMeetingOutcome($activity),\n 'internalMeetingNotes' => $decorator->generateDescription($activity),\n ];\n\n // Only if they are creating a fresh engagement should we update the times, otherwise it will cause a cal sync.\n if (! $activity->hasCrmProviderId()) {\n if ($activity->hasActualStartTime() && $activity->hasActualEndTime()) {\n $metadata['startTime'] = $decorator->formatStartTime($activity);\n $metadata['endTime'] = $decorator->formatEndTime($activity);\n }\n $metadata['title'] = $decorator->generateTitle($activity);\n }\n\n // For now, this is just a \"meetingOutcome\" field for some customers.\n $metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));\n\n return $this->upsertActivity($activity, $engagement, $metadata);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldDataRepository = app(FieldDataRepository::class);\n $fieldData = $fieldDataRepository->getActivityFieldData($activity, $objectType);\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->getField()->getCrmProviderId() => $data->getValue(),\n ];\n }\n\n return $payload;\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function upsertActivity(Activity $activity, array $engagement, array $metadata): Activity\n {\n if (! $activity->hasCrmProviderId()) {\n $this->createActivity($activity, $engagement, $metadata);\n\n return $activity;\n }\n\n try {\n $oldEngagement = $this->getClient()->getEngagementData($activity->getCrmProviderId());\n } catch (HubspotException $e) {\n $this->logger->warning('[HubSpot] Engagement not found', [\n 'activity_id' => $activity->getUuid(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'exception' => $e->getMessage(),\n ]);\n\n // potentially here we can log new activity if it is not found\n\n return $activity;\n }\n\n $type = $oldEngagement['engagement']['type'] ?? null;\n $bodyAttribute = $activity->isTypeConference() ? 'internalMeetingNotes' : 'body';\n\n $decorator = $this->getDecorateActivity();\n\n if ($type !== 'TASK') {\n $oldDescription = $oldEngagement['metadata'][$bodyAttribute] ?? '';\n $metadata[$bodyAttribute] = $decorator->mergeDescriptions(\n $metadata[$bodyAttribute],\n $oldDescription\n );\n\n $oldAssociations = $oldEngagement['associations'] ?? [];\n $this->updateNonTaskActivity($activity, $engagement, $metadata, $oldAssociations);\n } else {\n $oldTaskBody = $oldEngagement['metadata']['body'] ?? '';\n $metadata[$bodyAttribute] = $decorator->mergeDescriptions(\n $metadata[$bodyAttribute],\n $oldTaskBody\n );\n $this->updateTask($activity, $engagement, $metadata);\n }\n\n return $activity;\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function updateNonTaskActivity(\n Activity $activity,\n array $engagement,\n array $metadata,\n array $oldAssociations\n ): void {\n if ($activity->isTypeConference()) {\n $this->updateMeetingV3($activity->getCrmProviderId(), $engagement, $metadata);\n } else {\n $this->getClient()->updateEngagement($activity->getCrmProviderId(), $engagement, $metadata);\n }\n\n $this->updateActivityAssociations($activity, $oldAssociations);\n\n $this->logCrmEngagementManipulation(\n self::ACTION_UPDATE,\n ['crmId' => $activity->getCrmProviderId()],\n $metadata,\n );\n }\n\n private function updateActivityAssociations(Activity $activity, array $oldAssociations): void\n {\n $currentAssociations = $this->getActivityAssociations($activity);\n $associationChanges = $this->getAssociationDifferences($activity, $oldAssociations, $currentAssociations);\n\n // No changes - exit\n if (empty($associationChanges)) {\n return;\n }\n\n $this->logger->info('[HubSpot] Updating associations', [\n 'team' => $this->team->getUuid(),\n 'activity' => $activity->getUuid(),\n 'associationChanges' => $associationChanges,\n ]);\n\n $this->updateAssociations($activity, $associationChanges);\n }\n\n private function getAssociationDifferences(\n Activity $activity,\n array $oldAssociations,\n array $currentAssociations\n ): array {\n $objects = ['contactIds', 'companyIds', 'dealIds'];\n $changes = [];\n\n foreach ($objects as $object) {\n $oldIds = $this->normalizeIds($oldAssociations[$object] ?? []);\n $currentIds = $this->normalizeIds($currentAssociations[$object] ?? []);\n\n $added = array_diff($currentIds, $oldIds);\n $removed = array_diff($oldIds, $currentIds);\n\n $type = match ($object) {\n 'contactIds' => 'contact',\n 'companyIds' => 'company',\n 'dealIds' => 'deal',\n };\n\n $shouldIncludeRemoved = $this->shouldIncludeRemovedAssociations($type, $added, $activity);\n\n if (! empty($removed) && ! $shouldIncludeRemoved) {\n $this->logger->info('[HubSpot] Skipping association removal', [\n 'team' => $this->team->getUuid(),\n 'type' => $type,\n 'oldIds' => $oldIds,\n 'currentIds' => $currentIds,\n 'skippedRemovals' => array_values($removed),\n ]);\n }\n\n if (! empty($added) || (! empty($removed) && $shouldIncludeRemoved)) {\n $changes[$type] = [\n 'added' => array_values($added),\n 'removed' => array_values($removed),\n ];\n }\n }\n\n return $changes;\n }\n\n /**\n * Determines whether removed associations should be synced to HubSpot.\n *\n * For contacts and companies, we always sync removals (original behavior).\n * For deals, we only sync removals when:\n * - There are new deals being added (replacement scenario), OR\n * - The activity has an account associated (indicating intentional association management)\n *\n * This prevents accidentally removing deal associations that exist in HubSpot\n * but not in Jiminny's database (e.g., deals manually added by users in HubSpot).\n */\n private function shouldIncludeRemovedAssociations(string $type, array $added, Activity $activity): bool\n {\n // Contacts and companies: always sync removals\n if ($type !== 'deal') {\n return true;\n }\n\n // Deals: sync removals if we're adding new deals (replacement)\n if (! empty($added)) {\n return true;\n }\n\n // Deals: sync removals only if activity has an account (intentional management)\n return $activity->hasAccount();\n }\n\n private function normalizeIds(array $ids): array\n {\n $stringIds = array_map('strval', $ids);\n $uniqueIds = array_unique($stringIds);\n sort($uniqueIds);\n\n return $uniqueIds;\n }\n\n private function updateAssociations(Activity $activity, array $associationChanges): void\n {\n $objectType = $activity->isTypeConference() ? 'meeting' : 'call';\n\n foreach ($associationChanges as $type => $changes) {\n if (! empty($changes['added'])) {\n $associationType = (new AssociationTypeIdV4())->getAssociationType($objectType, $type);\n $payload = $this->payloadBuilder->buildAddAssociationPayload(\n $activity->getCrmProviderId(),\n $changes['added'],\n $associationType\n );\n $this->getClient()->addAssociations($objectType, $type, $payload);\n }\n\n if (! empty($changes['removed'])) {\n $payload = $this->payloadBuilder->buildRemoveAssociationPayload(\n $activity->getCrmProviderId(),\n $changes['removed']\n );\n $this->getClient()->removeAssociations($objectType, $type, $payload);\n }\n }\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function updateMeetingV3(string $meetingId, array $engagement, array $metadata): Response\n {\n // If already set by us/client, do not override it\n if (isset($engagement['activityType']) && $this->hasEngagementActivityType($meetingId)) {\n $this->logger->info('[HubSpot] Meeting activity type already set', [\n 'meetingId' => $meetingId,\n 'activityType' => $engagement['activityType'],\n ]);\n\n unset($engagement['activityType']);\n }\n\n $payload = $this->payloadBuilder->getV3MeetingPayload($engagement, $metadata);\n\n return $this->getClient()->updateMeeting($meetingId, $payload);\n }\n\n private function hasEngagementActivityType(string $engagementId): bool\n {\n try {\n $engagementData = $this->getClient()->getEngagementData($engagementId);\n if (isset($engagementData['engagement']['activityType']) && trim($engagementData['engagement']['activityType']) != '') {\n return true;\n }\n\n return false;\n } catch (\\Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->info('[HubSpot] Exception checking engagement activity type, defaulting to preserve existing', [\n 'engagementId' => $engagementId,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n return true;\n }\n\n private function updateTask(Activity $activity, array $engagement, array $metadata): void\n {\n $this->getClient()->deleteEngagement($activity->getCrmProviderId());\n\n $this->logCrmEngagementManipulation(\n self::ACTION_DELETE,\n ['crmId' => $activity->getCrmProviderId()],\n );\n\n $this->createActivity($activity, $engagement, $metadata);\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function createActivity(Activity $activity, array $engagement, array $metadata): void\n {\n $associations = $this->getActivityAssociations($activity);\n $associationsV4 = $this->convertActivityMeetingAssociationsV4($activity);\n\n if ($activity->isTypeConference()) {\n try {\n $hsEngagement = $this->createMeetingV3($engagement, $associationsV4, $metadata);\n $activityId = $hsEngagement->data->id;\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associationsV4);\n\n $activity->crm_provider_id = $activityId;\n $activity->save();\n } catch (BadRequest $exception) {\n Sentry::captureException($exception);\n\n $this->logger->warning('[HubSpot] Error while creating engagements', [\n 'activity' => $activity->getUuid(),\n 'message' => $exception->getMessage(),\n 'engagement' => $engagement,\n 'associations' => $associations,\n 'metadata' => $metadata,\n ]);\n }\n } else {\n try {\n $hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);\n $activityId = $hsEngagement->data->engagement->id;\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n $activity->crm_provider_id = $activityId;\n $activity->save();\n } catch (BadRequest $exception) {\n Sentry::captureException($exception);\n\n $this->logger->warning('[HubSpot] Error while creating engagements', [\n 'activity' => $activity->getUuid(),\n 'message' => $exception->getMessage(),\n 'engagement' => $engagement,\n 'associations' => $associations,\n 'metadata' => $metadata,\n ]);\n }\n }\n }\n\n private function convertActivityMeetingAssociationsV4(Activity $activity): array\n {\n $associations = [];\n\n $contactIds = $this->getParticipantsIds($activity);\n\n foreach ($contactIds as $contactId) {\n $associations[] = $this->buildAssociation(\n (int) $contactId,\n [AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_CONTACT]\n );\n }\n\n if ($activity->hasAccount()) {\n $crmProviderId = $activity->getAccount()?->getCrmProviderId();\n if ($crmProviderId) {\n $associations[] = $this->buildAssociation(\n (int) $crmProviderId,\n [AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_COMPANY]\n );\n }\n }\n\n if ($activity->hasOpportunity()) {\n $crmProviderId = $activity->getOpportunity()?->getCrmProviderId();\n if ($crmProviderId) {\n $associations[] = $this->buildAssociation(\n (int) $crmProviderId,\n [AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_DEAL]\n );\n }\n }\n\n return $associations;\n }\n\n private function buildAssociation(int $id, array $categoryToTypeIds): array\n {\n $types = [];\n\n foreach ($categoryToTypeIds as $category => $typeId) {\n $types[] = $this->buildAssociationType($category, $typeId);\n }\n\n return [\n 'to' => ['id' => (string) $id],\n 'types' => $types,\n ];\n }\n\n private function buildAssociationType(string $category, int $typeId): array\n {\n return [\n 'associationCategory' => $category,\n 'associationTypeId' => $typeId,\n ];\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function createMeetingV3(array $engagement, array $associations, array $metadata): Response\n {\n $payload = $this->payloadBuilder->getV3MeetingPayload(\n engagement: $engagement,\n metadata: $metadata,\n associations: $associations\n );\n\n return $this->getClient()->createMeeting($payload);\n }\n\n /**\n * @throws BadRequest\n * @throws HubspotException\n */\n private function buildSoftphonePayload(Activity $activity): Activity\n {\n $decorator = $this->getDecorateActivity();\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $decorator->formatCreatedAt($activity),\n 'type' => 'CALL',\n ];\n\n if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {\n $engagement['activityType'] = $activity->getActivityType()->getName();\n }\n\n $metadata = [\n 'toNumber' => $decorator->formatCallToParticipant($activity),\n 'fromNumber' => $activity->getFromParticipant()?->getPhoneNumber(),\n 'status' => $decorator->convertCallStatus($activity),\n 'durationMilliseconds' => (int) $activity->getDuration() * 1000,\n 'body' => $decorator->generateDescription($activity),\n ];\n\n // For now, this is just a \"disposition\" field to store Call Outcome.\n $metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));\n\n return $this->upsertActivity($activity, $engagement, $metadata);\n }\n\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $decorator = $this->getDecorateActivity();\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $decorator->formatCreatedAt($activity),\n 'type' => 'NOTE',\n ];\n\n $metadata = [\n 'body' => $decorator->generateDescription($activity),\n ];\n\n return $this->upsertActivity($activity, $engagement, $metadata);\n }\n\n private function getActivityAssociations(Activity $activity): array\n {\n return [\n 'contactIds' => $this->getParticipantsIds($activity),\n 'companyIds' => $activity->hasAccount() ? [$activity->getAccount()->getCrmProviderId()] : [],\n 'dealIds' => $activity->hasOpportunity() ? [$activity->getOpportunity()->getCrmProviderId()] : [],\n 'ownerIds' => [],\n ];\n }\n\n /**\n * Get DecorateActivity instance. Can be overridden in tests for mocking.\n */\n protected function getDecorateActivity(): DecorateActivity\n {\n return new DecorateActivity();\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n if (empty($fields['subject'])) {\n return null;\n }\n\n $associations = $this->getActivityAssociations($activity);\n\n if (empty($fields['timestamp']) === false) {\n $formatTimestamp = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['timestamp']);\n $timestamp = $formatTimestamp->getTimestamp();\n } else {\n $timestamp = strtotime('+1 day');\n }\n\n $reminder = null;\n if (empty($fields['reminder']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder']);\n $reminder = $formatReminder->getTimestamp() * 1000;\n }\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $timestamp * 1000,\n 'type' => 'TASK',\n ];\n\n $metadata = [\n 'subject' => $fields['subject'],\n 'body' => '',\n 'status' => 'NOT_STARTED',\n 'taskType' => 'CALL',\n 'reminders' => $reminder ? [$reminder] : [],\n ];\n\n try {\n $hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);\n } catch (BadRequest $e) {\n $this->logger->info('[HubSpot] Failed to create followup task', [\n 'activity' => $activity->getUuid(),\n 'engagement' => $engagement,\n 'metadata' => $metadata,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n // We don't actually create a corresponding activity object on our side yet.\n return (string) $hsEngagement->data->engagement->id;\n }\n\n private function logCrmEngagementManipulation(\n string $action,\n array $engagementData,\n array $data = [],\n array $associations = [],\n ): void {\n $payload = ['team' => $this->team->getUuid()];\n\n if ($action === self::ACTION_CREATE) {\n $payload['engagementData'] = $engagementData;\n $payload['data'] = $data;\n $payload['associations'] = $associations;\n }\n\n if ($action === self::ACTION_UPDATE) {\n $payload['engagementId'] = $engagementData['crmId'];\n $payload['data'] = $data;\n }\n\n if ($action === self::ACTION_DELETE) {\n $payload['engagementId'] = $engagementData['crmId'];\n }\n\n $this->logger->info('[HubSpot] Engagement manipulated (' . $action . ')', $payload);\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Hubspot\\Utils\\AssociationCategoryV4;\nuse Jiminny\\Services\\Crm\\Hubspot\\Utils\\AssociationTypeIdV4;\nuse SevenShores\\Hubspot\\Exceptions\\BadRequest;\nuse SevenShores\\Hubspot\\Http\\Response;\nuse SevenShores\\Hubspot\\Exceptions\\HubspotException;\nuse Sentry;\n\ntrait WriteCrmTrait\n{\n private const string ACTION_CREATE = 'create';\n private const string ACTION_UPDATE = 'update';\n private const string ACTION_DELETE = 'delete';\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->getCrmType()) {\n case Activity::TYPE_CONFERENCE:\n $activity = $this->buildConferencePayload($activity);\n\n break;\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildSoftphonePayload($activity);\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function buildConferencePayload(Activity $activity): Activity\n {\n $decorator = $this->getDecorateActivity();\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $decorator->formatStartTime($activity),\n 'type' => 'MEETING',\n ];\n\n if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {\n $engagement['activityType'] = $activity->getActivityType()->getName();\n }\n\n $metadata = [\n 'meetingOutcome' => $decorator->convertMeetingOutcome($activity),\n 'internalMeetingNotes' => $decorator->generateDescription($activity),\n ];\n\n // Only if they are creating a fresh engagement should we update the times, otherwise it will cause a cal sync.\n if (! $activity->hasCrmProviderId()) {\n if ($activity->hasActualStartTime() && $activity->hasActualEndTime()) {\n $metadata['startTime'] = $decorator->formatStartTime($activity);\n $metadata['endTime'] = $decorator->formatEndTime($activity);\n }\n $metadata['title'] = $decorator->generateTitle($activity);\n }\n\n // For now, this is just a \"meetingOutcome\" field for some customers.\n $metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));\n\n return $this->upsertActivity($activity, $engagement, $metadata);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldDataRepository = app(FieldDataRepository::class);\n $fieldData = $fieldDataRepository->getActivityFieldData($activity, $objectType);\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->getField()->getCrmProviderId() => $data->getValue(),\n ];\n }\n\n return $payload;\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function upsertActivity(Activity $activity, array $engagement, array $metadata): Activity\n {\n if (! $activity->hasCrmProviderId()) {\n $this->createActivity($activity, $engagement, $metadata);\n\n return $activity;\n }\n\n try {\n $oldEngagement = $this->getClient()->getEngagementData($activity->getCrmProviderId());\n } catch (HubspotException $e) {\n $this->logger->warning('[HubSpot] Engagement not found', [\n 'activity_id' => $activity->getUuid(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'exception' => $e->getMessage(),\n ]);\n\n // potentially here we can log new activity if it is not found\n\n return $activity;\n }\n\n $type = $oldEngagement['engagement']['type'] ?? null;\n $bodyAttribute = $activity->isTypeConference() ? 'internalMeetingNotes' : 'body';\n\n $decorator = $this->getDecorateActivity();\n\n if ($type !== 'TASK') {\n $oldDescription = $oldEngagement['metadata'][$bodyAttribute] ?? '';\n $metadata[$bodyAttribute] = $decorator->mergeDescriptions(\n $metadata[$bodyAttribute],\n $oldDescription\n );\n\n $oldAssociations = $oldEngagement['associations'] ?? [];\n $this->updateNonTaskActivity($activity, $engagement, $metadata, $oldAssociations);\n } else {\n $oldTaskBody = $oldEngagement['metadata']['body'] ?? '';\n $metadata[$bodyAttribute] = $decorator->mergeDescriptions(\n $metadata[$bodyAttribute],\n $oldTaskBody\n );\n $this->updateTask($activity, $engagement, $metadata);\n }\n\n return $activity;\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function updateNonTaskActivity(\n Activity $activity,\n array $engagement,\n array $metadata,\n array $oldAssociations\n ): void {\n if ($activity->isTypeConference()) {\n $this->updateMeetingV3($activity->getCrmProviderId(), $engagement, $metadata);\n } else {\n $this->getClient()->updateEngagement($activity->getCrmProviderId(), $engagement, $metadata);\n }\n\n $this->updateActivityAssociations($activity, $oldAssociations);\n\n $this->logCrmEngagementManipulation(\n self::ACTION_UPDATE,\n ['crmId' => $activity->getCrmProviderId()],\n $metadata,\n );\n }\n\n private function updateActivityAssociations(Activity $activity, array $oldAssociations): void\n {\n $currentAssociations = $this->getActivityAssociations($activity);\n $associationChanges = $this->getAssociationDifferences($activity, $oldAssociations, $currentAssociations);\n\n // No changes - exit\n if (empty($associationChanges)) {\n return;\n }\n\n $this->logger->info('[HubSpot] Updating associations', [\n 'team' => $this->team->getUuid(),\n 'activity' => $activity->getUuid(),\n 'associationChanges' => $associationChanges,\n ]);\n\n $this->updateAssociations($activity, $associationChanges);\n }\n\n private function getAssociationDifferences(\n Activity $activity,\n array $oldAssociations,\n array $currentAssociations\n ): array {\n $objects = ['contactIds', 'companyIds', 'dealIds'];\n $changes = [];\n\n foreach ($objects as $object) {\n $oldIds = $this->normalizeIds($oldAssociations[$object] ?? []);\n $currentIds = $this->normalizeIds($currentAssociations[$object] ?? []);\n\n $added = array_diff($currentIds, $oldIds);\n $removed = array_diff($oldIds, $currentIds);\n\n $type = match ($object) {\n 'contactIds' => 'contact',\n 'companyIds' => 'company',\n 'dealIds' => 'deal',\n };\n\n $shouldIncludeRemoved = $this->shouldIncludeRemovedAssociations($type, $added, $activity);\n\n if (! empty($removed) && ! $shouldIncludeRemoved) {\n $this->logger->info('[HubSpot] Skipping association removal', [\n 'team' => $this->team->getUuid(),\n 'type' => $type,\n 'oldIds' => $oldIds,\n 'currentIds' => $currentIds,\n 'skippedRemovals' => array_values($removed),\n ]);\n }\n\n if (! empty($added) || (! empty($removed) && $shouldIncludeRemoved)) {\n $changes[$type] = [\n 'added' => array_values($added),\n 'removed' => array_values($removed),\n ];\n }\n }\n\n return $changes;\n }\n\n /**\n * Determines whether removed associations should be synced to HubSpot.\n *\n * For contacts and companies, we always sync removals (original behavior).\n * For deals, we only sync removals when:\n * - There are new deals being added (replacement scenario), OR\n * - The activity has an account associated (indicating intentional association management)\n *\n * This prevents accidentally removing deal associations that exist in HubSpot\n * but not in Jiminny's database (e.g., deals manually added by users in HubSpot).\n */\n private function shouldIncludeRemovedAssociations(string $type, array $added, Activity $activity): bool\n {\n // Contacts and companies: always sync removals\n if ($type !== 'deal') {\n return true;\n }\n\n // Deals: sync removals if we're adding new deals (replacement)\n if (! empty($added)) {\n return true;\n }\n\n // Deals: sync removals only if activity has an account (intentional management)\n return $activity->hasAccount();\n }\n\n private function normalizeIds(array $ids): array\n {\n $stringIds = array_map('strval', $ids);\n $uniqueIds = array_unique($stringIds);\n sort($uniqueIds);\n\n return $uniqueIds;\n }\n\n private function updateAssociations(Activity $activity, array $associationChanges): void\n {\n $objectType = $activity->isTypeConference() ? 'meeting' : 'call';\n\n foreach ($associationChanges as $type => $changes) {\n if (! empty($changes['added'])) {\n $associationType = (new AssociationTypeIdV4())->getAssociationType($objectType, $type);\n $payload = $this->payloadBuilder->buildAddAssociationPayload(\n $activity->getCrmProviderId(),\n $changes['added'],\n $associationType\n );\n $this->getClient()->addAssociations($objectType, $type, $payload);\n }\n\n if (! empty($changes['removed'])) {\n $payload = $this->payloadBuilder->buildRemoveAssociationPayload(\n $activity->getCrmProviderId(),\n $changes['removed']\n );\n $this->getClient()->removeAssociations($objectType, $type, $payload);\n }\n }\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function updateMeetingV3(string $meetingId, array $engagement, array $metadata): Response\n {\n // If already set by us/client, do not override it\n if (isset($engagement['activityType']) && $this->hasEngagementActivityType($meetingId)) {\n $this->logger->info('[HubSpot] Meeting activity type already set', [\n 'meetingId' => $meetingId,\n 'activityType' => $engagement['activityType'],\n ]);\n\n unset($engagement['activityType']);\n }\n\n $payload = $this->payloadBuilder->getV3MeetingPayload($engagement, $metadata);\n\n return $this->getClient()->updateMeeting($meetingId, $payload);\n }\n\n private function hasEngagementActivityType(string $engagementId): bool\n {\n try {\n $engagementData = $this->getClient()->getEngagementData($engagementId);\n if (isset($engagementData['engagement']['activityType']) && trim($engagementData['engagement']['activityType']) != '') {\n return true;\n }\n\n return false;\n } catch (\\Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->info('[HubSpot] Exception checking engagement activity type, defaulting to preserve existing', [\n 'engagementId' => $engagementId,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n return true;\n }\n\n private function updateTask(Activity $activity, array $engagement, array $metadata): void\n {\n $this->getClient()->deleteEngagement($activity->getCrmProviderId());\n\n $this->logCrmEngagementManipulation(\n self::ACTION_DELETE,\n ['crmId' => $activity->getCrmProviderId()],\n );\n\n $this->createActivity($activity, $engagement, $metadata);\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function createActivity(Activity $activity, array $engagement, array $metadata): void\n {\n $associations = $this->getActivityAssociations($activity);\n $associationsV4 = $this->convertActivityMeetingAssociationsV4($activity);\n\n if ($activity->isTypeConference()) {\n try {\n $hsEngagement = $this->createMeetingV3($engagement, $associationsV4, $metadata);\n $activityId = $hsEngagement->data->id;\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associationsV4);\n\n $activity->crm_provider_id = $activityId;\n $activity->save();\n } catch (BadRequest $exception) {\n Sentry::captureException($exception);\n\n $this->logger->warning('[HubSpot] Error while creating engagements', [\n 'activity' => $activity->getUuid(),\n 'message' => $exception->getMessage(),\n 'engagement' => $engagement,\n 'associations' => $associations,\n 'metadata' => $metadata,\n ]);\n }\n } else {\n try {\n $hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);\n $activityId = $hsEngagement->data->engagement->id;\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n $activity->crm_provider_id = $activityId;\n $activity->save();\n } catch (BadRequest $exception) {\n Sentry::captureException($exception);\n\n $this->logger->warning('[HubSpot] Error while creating engagements', [\n 'activity' => $activity->getUuid(),\n 'message' => $exception->getMessage(),\n 'engagement' => $engagement,\n 'associations' => $associations,\n 'metadata' => $metadata,\n ]);\n }\n }\n }\n\n private function convertActivityMeetingAssociationsV4(Activity $activity): array\n {\n $associations = [];\n\n $contactIds = $this->getParticipantsIds($activity);\n\n foreach ($contactIds as $contactId) {\n $associations[] = $this->buildAssociation(\n (int) $contactId,\n [AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_CONTACT]\n );\n }\n\n if ($activity->hasAccount()) {\n $crmProviderId = $activity->getAccount()?->getCrmProviderId();\n if ($crmProviderId) {\n $associations[] = $this->buildAssociation(\n (int) $crmProviderId,\n [AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_COMPANY]\n );\n }\n }\n\n if ($activity->hasOpportunity()) {\n $crmProviderId = $activity->getOpportunity()?->getCrmProviderId();\n if ($crmProviderId) {\n $associations[] = $this->buildAssociation(\n (int) $crmProviderId,\n [AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_DEAL]\n );\n }\n }\n\n return $associations;\n }\n\n private function buildAssociation(int $id, array $categoryToTypeIds): array\n {\n $types = [];\n\n foreach ($categoryToTypeIds as $category => $typeId) {\n $types[] = $this->buildAssociationType($category, $typeId);\n }\n\n return [\n 'to' => ['id' => (string) $id],\n 'types' => $types,\n ];\n }\n\n private function buildAssociationType(string $category, int $typeId): array\n {\n return [\n 'associationCategory' => $category,\n 'associationTypeId' => $typeId,\n ];\n }\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function createMeetingV3(array $engagement, array $associations, array $metadata): Response\n {\n $payload = $this->payloadBuilder->getV3MeetingPayload(\n engagement: $engagement,\n metadata: $metadata,\n associations: $associations\n );\n\n return $this->getClient()->createMeeting($payload);\n }\n\n /**\n * @throws BadRequest\n * @throws HubspotException\n */\n private function buildSoftphonePayload(Activity $activity): Activity\n {\n $decorator = $this->getDecorateActivity();\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $decorator->formatCreatedAt($activity),\n 'type' => 'CALL',\n ];\n\n if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {\n $engagement['activityType'] = $activity->getActivityType()->getName();\n }\n\n $metadata = [\n 'toNumber' => $decorator->formatCallToParticipant($activity),\n 'fromNumber' => $activity->getFromParticipant()?->getPhoneNumber(),\n 'status' => $decorator->convertCallStatus($activity),\n 'durationMilliseconds' => (int) $activity->getDuration() * 1000,\n 'body' => $decorator->generateDescription($activity),\n ];\n\n // For now, this is just a \"disposition\" field to store Call Outcome.\n $metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));\n\n return $this->upsertActivity($activity, $engagement, $metadata);\n }\n\n\n /**\n * @throws HubspotException\n * @throws BadRequest\n */\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $decorator = $this->getDecorateActivity();\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $decorator->formatCreatedAt($activity),\n 'type' => 'NOTE',\n ];\n\n $metadata = [\n 'body' => $decorator->generateDescription($activity),\n ];\n\n return $this->upsertActivity($activity, $engagement, $metadata);\n }\n\n private function getActivityAssociations(Activity $activity): array\n {\n return [\n 'contactIds' => $this->getParticipantsIds($activity),\n 'companyIds' => $activity->hasAccount() ? [$activity->getAccount()->getCrmProviderId()] : [],\n 'dealIds' => $activity->hasOpportunity() ? [$activity->getOpportunity()->getCrmProviderId()] : [],\n 'ownerIds' => [],\n ];\n }\n\n /**\n * Get DecorateActivity instance. Can be overridden in tests for mocking.\n */\n protected function getDecorateActivity(): DecorateActivity\n {\n return new DecorateActivity();\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n if (empty($fields['subject'])) {\n return null;\n }\n\n $associations = $this->getActivityAssociations($activity);\n\n if (empty($fields['timestamp']) === false) {\n $formatTimestamp = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['timestamp']);\n $timestamp = $formatTimestamp->getTimestamp();\n } else {\n $timestamp = strtotime('+1 day');\n }\n\n $reminder = null;\n if (empty($fields['reminder']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder']);\n $reminder = $formatReminder->getTimestamp() * 1000;\n }\n\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->getCrmProviderId(),\n 'timestamp' => $timestamp * 1000,\n 'type' => 'TASK',\n ];\n\n $metadata = [\n 'subject' => $fields['subject'],\n 'body' => '',\n 'status' => 'NOT_STARTED',\n 'taskType' => 'CALL',\n 'reminders' => $reminder ? [$reminder] : [],\n ];\n\n try {\n $hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);\n } catch (BadRequest $e) {\n $this->logger->info('[HubSpot] Failed to create followup task', [\n 'activity' => $activity->getUuid(),\n 'engagement' => $engagement,\n 'metadata' => $metadata,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n // We don't actually create a corresponding activity object on our side yet.\n return (string) $hsEngagement->data->engagement->id;\n }\n\n private function logCrmEngagementManipulation(\n string $action,\n array $engagementData,\n array $data = [],\n array $associations = [],\n ): void {\n $payload = ['team' => $this->team->getUuid()];\n\n if ($action === self::ACTION_CREATE) {\n $payload['engagementData'] = $engagementData;\n $payload['data'] = $data;\n $payload['associations'] = $associations;\n }\n\n if ($action === self::ACTION_UPDATE) {\n $payload['engagementId'] = $engagementData['crmId'];\n $payload['data'] = $data;\n }\n\n if ($action === self::ACTION_DELETE) {\n $payload['engagementId'] = $engagementData['crmId'];\n }\n\n $this->logger->info('[HubSpot] Engagement manipulated (' . $action . ')', $payload);\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-2316546239645567936
|
6551498163460912845
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Code changed:
Hide
Sync Changes
Hide This Notification
8
6
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Field;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Services\Crm\Hubspot\DecorateActivity;
use Jiminny\Services\Crm\Hubspot\Utils\AssociationCategoryV4;
use Jiminny\Services\Crm\Hubspot\Utils\AssociationTypeIdV4;
use SevenShores\Hubspot\Exceptions\BadRequest;
use SevenShores\Hubspot\Http\Response;
use SevenShores\Hubspot\Exceptions\HubspotException;
use Sentry;
trait WriteCrmTrait
{
private const string ACTION_CREATE = 'create';
private const string ACTION_UPDATE = 'update';
private const string ACTION_DELETE = 'delete';
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->getCrmType()) {
case Activity::TYPE_CONFERENCE:
$activity = $this->buildConferencePayload($activity);
break;
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildSoftphonePayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
break;
}
return $activity;
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function buildConferencePayload(Activity $activity): Activity
{
$decorator = $this->getDecorateActivity();
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $decorator->formatStartTime($activity),
'type' => 'MEETING',
];
if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {
$engagement['activityType'] = $activity->getActivityType()->getName();
}
$metadata = [
'meetingOutcome' => $decorator->convertMeetingOutcome($activity),
'internalMeetingNotes' => $decorator->generateDescription($activity),
];
// Only if they are creating a fresh engagement should we update the times, otherwise it will cause a cal sync.
if (! $activity->hasCrmProviderId()) {
if ($activity->hasActualStartTime() && $activity->hasActualEndTime()) {
$metadata['startTime'] = $decorator->formatStartTime($activity);
$metadata['endTime'] = $decorator->formatEndTime($activity);
}
$metadata['title'] = $decorator->generateTitle($activity);
}
// For now, this is just a "meetingOutcome" field for some customers.
$metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));
return $this->upsertActivity($activity, $engagement, $metadata);
}
private function fetchCustomFieldData(Activity $activity, string $objectType): array
{
$payload = [];
$fieldDataRepository = app(FieldDataRepository::class);
$fieldData = $fieldDataRepository->getActivityFieldData($activity, $objectType);
foreach ($fieldData as $data) {
// Add the field and value to the payload.
$payload += [
$data->getField()->getCrmProviderId() => $data->getValue(),
];
}
return $payload;
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function upsertActivity(Activity $activity, array $engagement, array $metadata): Activity
{
if (! $activity->hasCrmProviderId()) {
$this->createActivity($activity, $engagement, $metadata);
return $activity;
}
try {
$oldEngagement = $this->getClient()->getEngagementData($activity->getCrmProviderId());
} catch (HubspotException $e) {
$this->logger->warning('[HubSpot] Engagement not found', [
'activity_id' => $activity->getUuid(),
'crm_provider_id' => $activity->getCrmProviderId(),
'exception' => $e->getMessage(),
]);
// potentially here we can log new activity if it is not found
return $activity;
}
$type = $oldEngagement['engagement']['type'] ?? null;
$bodyAttribute = $activity->isTypeConference() ? 'internalMeetingNotes' : 'body';
$decorator = $this->getDecorateActivity();
if ($type !== 'TASK') {
$oldDescription = $oldEngagement['metadata'][$bodyAttribute] ?? '';
$metadata[$bodyAttribute] = $decorator->mergeDescriptions(
$metadata[$bodyAttribute],
$oldDescription
);
$oldAssociations = $oldEngagement['associations'] ?? [];
$this->updateNonTaskActivity($activity, $engagement, $metadata, $oldAssociations);
} else {
$oldTaskBody = $oldEngagement['metadata']['body'] ?? '';
$metadata[$bodyAttribute] = $decorator->mergeDescriptions(
$metadata[$bodyAttribute],
$oldTaskBody
);
$this->updateTask($activity, $engagement, $metadata);
}
return $activity;
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function updateNonTaskActivity(
Activity $activity,
array $engagement,
array $metadata,
array $oldAssociations
): void {
if ($activity->isTypeConference()) {
$this->updateMeetingV3($activity->getCrmProviderId(), $engagement, $metadata);
} else {
$this->getClient()->updateEngagement($activity->getCrmProviderId(), $engagement, $metadata);
}
$this->updateActivityAssociations($activity, $oldAssociations);
$this->logCrmEngagementManipulation(
self::ACTION_UPDATE,
['crmId' => $activity->getCrmProviderId()],
$metadata,
);
}
private function updateActivityAssociations(Activity $activity, array $oldAssociations): void
{
$currentAssociations = $this->getActivityAssociations($activity);
$associationChanges = $this->getAssociationDifferences($activity, $oldAssociations, $currentAssociations);
// No changes - exit
if (empty($associationChanges)) {
return;
}
$this->logger->info('[HubSpot] Updating associations', [
'team' => $this->team->getUuid(),
'activity' => $activity->getUuid(),
'associationChanges' => $associationChanges,
]);
$this->updateAssociations($activity, $associationChanges);
}
private function getAssociationDifferences(
Activity $activity,
array $oldAssociations,
array $currentAssociations
): array {
$objects = ['contactIds', 'companyIds', 'dealIds'];
$changes = [];
foreach ($objects as $object) {
$oldIds = $this->normalizeIds($oldAssociations[$object] ?? []);
$currentIds = $this->normalizeIds($currentAssociations[$object] ?? []);
$added = array_diff($currentIds, $oldIds);
$removed = array_diff($oldIds, $currentIds);
$type = match ($object) {
'contactIds' => 'contact',
'companyIds' => 'company',
'dealIds' => 'deal',
};
$shouldIncludeRemoved = $this->shouldIncludeRemovedAssociations($type, $added, $activity);
if (! empty($removed) && ! $shouldIncludeRemoved) {
$this->logger->info('[HubSpot] Skipping association removal', [
'team' => $this->team->getUuid(),
'type' => $type,
'oldIds' => $oldIds,
'currentIds' => $currentIds,
'skippedRemovals' => array_values($removed),
]);
}
if (! empty($added) || (! empty($removed) && $shouldIncludeRemoved)) {
$changes[$type] = [
'added' => array_values($added),
'removed' => array_values($removed),
];
}
}
return $changes;
}
/**
* Determines whether removed associations should be synced to HubSpot.
*
* For contacts and companies, we always sync removals (original behavior).
* For deals, we only sync removals when:
* - There are new deals being added (replacement scenario), OR
* - The activity has an account associated (indicating intentional association management)
*
* This prevents accidentally removing deal associations that exist in HubSpot
* but not in Jiminny's database (e.g., deals manually added by users in HubSpot).
*/
private function shouldIncludeRemovedAssociations(string $type, array $added, Activity $activity): bool
{
// Contacts and companies: always sync removals
if ($type !== 'deal') {
return true;
}
// Deals: sync removals if we're adding new deals (replacement)
if (! empty($added)) {
return true;
}
// Deals: sync removals only if activity has an account (intentional management)
return $activity->hasAccount();
}
private function normalizeIds(array $ids): array
{
$stringIds = array_map('strval', $ids);
$uniqueIds = array_unique($stringIds);
sort($uniqueIds);
return $uniqueIds;
}
private function updateAssociations(Activity $activity, array $associationChanges): void
{
$objectType = $activity->isTypeConference() ? 'meeting' : 'call';
foreach ($associationChanges as $type => $changes) {
if (! empty($changes['added'])) {
$associationType = (new AssociationTypeIdV4())->getAssociationType($objectType, $type);
$payload = $this->payloadBuilder->buildAddAssociationPayload(
$activity->getCrmProviderId(),
$changes['added'],
$associationType
);
$this->getClient()->addAssociations($objectType, $type, $payload);
}
if (! empty($changes['removed'])) {
$payload = $this->payloadBuilder->buildRemoveAssociationPayload(
$activity->getCrmProviderId(),
$changes['removed']
);
$this->getClient()->removeAssociations($objectType, $type, $payload);
}
}
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function updateMeetingV3(string $meetingId, array $engagement, array $metadata): Response
{
// If already set by us/client, do not override it
if (isset($engagement['activityType']) && $this->hasEngagementActivityType($meetingId)) {
$this->logger->info('[HubSpot] Meeting activity type already set', [
'meetingId' => $meetingId,
'activityType' => $engagement['activityType'],
]);
unset($engagement['activityType']);
}
$payload = $this->payloadBuilder->getV3MeetingPayload($engagement, $metadata);
return $this->getClient()->updateMeeting($meetingId, $payload);
}
private function hasEngagementActivityType(string $engagementId): bool
{
try {
$engagementData = $this->getClient()->getEngagementData($engagementId);
if (isset($engagementData['engagement']['activityType']) && trim($engagementData['engagement']['activityType']) != '') {
return true;
}
return false;
} catch (\Exception $exception) {
Sentry::captureException($exception);
$this->logger->info('[HubSpot] Exception checking engagement activity type, defaulting to preserve existing', [
'engagementId' => $engagementId,
'exception' => $exception->getMessage(),
]);
}
return true;
}
private function updateTask(Activity $activity, array $engagement, array $metadata): void
{
$this->getClient()->deleteEngagement($activity->getCrmProviderId());
$this->logCrmEngagementManipulation(
self::ACTION_DELETE,
['crmId' => $activity->getCrmProviderId()],
);
$this->createActivity($activity, $engagement, $metadata);
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function createActivity(Activity $activity, array $engagement, array $metadata): void
{
$associations = $this->getActivityAssociations($activity);
$associationsV4 = $this->convertActivityMeetingAssociationsV4($activity);
if ($activity->isTypeConference()) {
try {
$hsEngagement = $this->createMeetingV3($engagement, $associationsV4, $metadata);
$activityId = $hsEngagement->data->id;
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associationsV4);
$activity->crm_provider_id = $activityId;
$activity->save();
} catch (BadRequest $exception) {
Sentry::captureException($exception);
$this->logger->warning('[HubSpot] Error while creating engagements', [
'activity' => $activity->getUuid(),
'message' => $exception->getMessage(),
'engagement' => $engagement,
'associations' => $associations,
'metadata' => $metadata,
]);
}
} else {
try {
$hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);
$activityId = $hsEngagement->data->engagement->id;
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);
$activity->crm_provider_id = $activityId;
$activity->save();
} catch (BadRequest $exception) {
Sentry::captureException($exception);
$this->logger->warning('[HubSpot] Error while creating engagements', [
'activity' => $activity->getUuid(),
'message' => $exception->getMessage(),
'engagement' => $engagement,
'associations' => $associations,
'metadata' => $metadata,
]);
}
}
}
private function convertActivityMeetingAssociationsV4(Activity $activity): array
{
$associations = [];
$contactIds = $this->getParticipantsIds($activity);
foreach ($contactIds as $contactId) {
$associations[] = $this->buildAssociation(
(int) $contactId,
[AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_CONTACT]
);
}
if ($activity->hasAccount()) {
$crmProviderId = $activity->getAccount()?->getCrmProviderId();
if ($crmProviderId) {
$associations[] = $this->buildAssociation(
(int) $crmProviderId,
[AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_COMPANY]
);
}
}
if ($activity->hasOpportunity()) {
$crmProviderId = $activity->getOpportunity()?->getCrmProviderId();
if ($crmProviderId) {
$associations[] = $this->buildAssociation(
(int) $crmProviderId,
[AssociationCategoryV4::HUBSPOT_DEFINED => AssociationTypeIdV4::MEETING_TO_DEAL]
);
}
}
return $associations;
}
private function buildAssociation(int $id, array $categoryToTypeIds): array
{
$types = [];
foreach ($categoryToTypeIds as $category => $typeId) {
$types[] = $this->buildAssociationType($category, $typeId);
}
return [
'to' => ['id' => (string) $id],
'types' => $types,
];
}
private function buildAssociationType(string $category, int $typeId): array
{
return [
'associationCategory' => $category,
'associationTypeId' => $typeId,
];
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function createMeetingV3(array $engagement, array $associations, array $metadata): Response
{
$payload = $this->payloadBuilder->getV3MeetingPayload(
engagement: $engagement,
metadata: $metadata,
associations: $associations
);
return $this->getClient()->createMeeting($payload);
}
/**
* @throws BadRequest
* @throws HubspotException
*/
private function buildSoftphonePayload(Activity $activity): Activity
{
$decorator = $this->getDecorateActivity();
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $decorator->formatCreatedAt($activity),
'type' => 'CALL',
];
if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())) {
$engagement['activityType'] = $activity->getActivityType()->getName();
}
$metadata = [
'toNumber' => $decorator->formatCallToParticipant($activity),
'fromNumber' => $activity->getFromParticipant()?->getPhoneNumber(),
'status' => $decorator->convertCallStatus($activity),
'durationMilliseconds' => (int) $activity->getDuration() * 1000,
'body' => $decorator->generateDescription($activity),
];
// For now, this is just a "disposition" field to store Call Outcome.
$metadata = array_merge($metadata, $this->fetchCustomFieldData($activity, Field::OBJECT_TASK));
return $this->upsertActivity($activity, $engagement, $metadata);
}
/**
* @throws HubspotException
* @throws BadRequest
*/
private function buildTextMessagePayload(Activity $activity): Activity
{
$decorator = $this->getDecorateActivity();
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $decorator->formatCreatedAt($activity),
'type' => 'NOTE',
];
$metadata = [
'body' => $decorator->generateDescription($activity),
];
return $this->upsertActivity($activity, $engagement, $metadata);
}
private function getActivityAssociations(Activity $activity): array
{
return [
'contactIds' => $this->getParticipantsIds($activity),
'companyIds' => $activity->hasAccount() ? [$activity->getAccount()->getCrmProviderId()] : [],
'dealIds' => $activity->hasOpportunity() ? [$activity->getOpportunity()->getCrmProviderId()] : [],
'ownerIds' => [],
];
}
/**
* Get DecorateActivity instance. Can be overridden in tests for mocking.
*/
protected function getDecorateActivity(): DecorateActivity
{
return new DecorateActivity();
}
public function saveFollowupActivity(Activity $activity, array $fields): ?string
{
if (empty($fields['subject'])) {
return null;
}
$associations = $this->getActivityAssociations($activity);
if (empty($fields['timestamp']) === false) {
$formatTimestamp = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $fields['timestamp']);
$timestamp = $formatTimestamp->getTimestamp();
} else {
$timestamp = strtotime('+1 day');
}
$reminder = null;
if (empty($fields['reminder']) === false) {
$formatReminder = Carbon::createFromFormat('Y-m-d\TH:i:s\Z', $fields['reminder']);
$reminder = $formatReminder->getTimestamp() * 1000;
}
$engagement = [
'active' => true,
'ownerId' => $this->profile->getCrmProviderId(),
'timestamp' => $timestamp * 1000,
'type' => 'TASK',
];
$metadata = [
'subject' => $fields['subject'],
'body' => '',
'status' => 'NOT_STARTED',
'taskType' => 'CALL',
'reminders' => $reminder ? [$reminder] : [],
];
try {
$hsEngagement = $this->getClient()->createEngagement($engagement, $associations, $metadata);
} catch (BadRequest $e) {
$this->logger->info('[HubSpot] Failed to create followup task', [
'activity' => $activity->getUuid(),
'engagement' => $engagement,
'metadata' => $metadata,
'error' => $e->getMessage(),
]);
return null;
}
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);
// We don't actually create a corresponding activity object on our side yet.
return (string) $hsEngagement->data->engagement->id;
}
private function logCrmEngagementManipulation(
string $action,
array $engagementData,
array $data = [],
array $associations = [],
): void {
$payload = ['team' => $this->team->getUuid()];
if ($action === self::ACTION_CREATE) {
$payload['engagementData'] = $engagementData;
$payload['data'] = $data;
$payload['associations'] = $associations;
}
if ($action === self::ACTION_UPDATE) {
$payload['engagementId'] = $engagementData['crmId'];
$payload['data'] = $data;
}
if ($action === self::ACTION_DELETE) {
$payload['engagementId'] = $engagementData['crmId'];
}
$this->logger->info('[HubSpot] Engagement manipulated (' . $action . ')', $payload);
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…...
|
45256
|
NULL
|
NULL
|
NULL
|
|
45260
|
1624
|
7
|
2026-05-14T14:27:44.274004+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768864274_m2.jpg...
|
PhpStorm
|
faVsco.js – WriteCrmTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7058342144550237105
|
-7195274138713862717
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterdav at 13.35Yesterday at 13:35Yesterday at 13.34Yesterdav at 13:33Yesterday at 13:32Yesterdav at 13:37Yesterday at 13:31Yesterday at 13.30Yesterdav at 13:30Yesterday at 13:29resterday at 15.4gYesterdav at 13:28Yesterday at 13:28Yesterday at 13:27Yesterdav at 13:26resterday at 13-4oYesterdav at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Voctorday at 12:22Yesterday at 13.21Yesterdav at 13:20Yesterdav at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13.17Yecterdav at 12:17Yesterdav at 13:16Yesterday at 13-10Yesterdav at 13:15Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:12Yesterday at 13.12Yesterdav at 13:12Yesterday at 13:11Yesterday at 13:10Yoctorday at 12:10Yesterdav at 13:09Yesterday at 13.09Yocterdav at 12:081Yesterdav at 13:08Yesterdav at 13:071S K:MPEG-4 movie16 KB17 KB29 Kb6 KE12 KB9 KB7 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPE0"4 movie8 KBMDSG-A movie37 KB10 KbMP2G-4 movie7 KBI8 KBMPEG-4 movieMPEG-4 movie8 K:72 KB14 KE13 K:MoECh movioMPEG-4 movieO KRI18 KB12 KBMPEG-1 movidMPEG-4 movie10 KEMPEG-4 movie16 KB MPEG-4 movie6 KB6 KB1MPEG-4 movie12 KB23 KB8 KBMDSG.A movicMPEG-4 movie6KE6 KBMPEG-4 movieMPEG-4 movie11 KB11 K:MPEG-4 movie20 kRMDEC A movid10 KBMPEG-4 movie7 KPMDEG-A movie5 KBMPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KB88 KBMPEG-4 movieMDEC.A movialMPEG-4 movieKO KRMDEG-A movie98 KBMPEG-4 movie97 KBMPEG-4 movie66 K:MPEG-A movie44 KB MPEG-4 movie93 KB78 KB50 kpMPEG-4 movieMDEG.A movio58 KB27 KBMPEG-4 movie7KP12 KBMADECA movid32 KB17 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zipreport(2).xmlAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentPDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archive5KRMarkdo…..umentWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 Mау 1/•2/.43)Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45259
|
1623
|
9
|
2026-05-14T14:27:44.274066+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768864274_m1.jpg...
|
PhpStorm
|
faVsco.js – WriteCrmTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vlhl100% (C47HandleHubspotRateLimitTestv8• Thu 14 May 17:27:44* :QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php= custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.php() WriteCrmTrait.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php18.••© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© ClosedDealStagesService.pt19C DealFieldsService.php55© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php62© HubspotClientinterface.php© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): Activity'active' = true,'ownerId'= Sthis->profile->getCrmProviderIdO,'timestamp' => $decorator->formatStartTime($activity),'type' => 'MEETING',88 ×6 л606163© HubspotTokenManager.php64]:© PayloadBuilder.php65© RemoteCrmObjectManipulat66ResponseNormalize.php67if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())){$engagement['activityType'] = $activity->getActivityType()->getName();© Service.php68© SyncFieldAction.php69© SyncRelatedActivityManage70© WebhookSyncBatchProcess71v D IntegrationApp72> [J Accessors$metadata = ['meetingOutcome' => $decorator->convertMeetingOutcome(Sactivity),'internalMeetingNotes'= $decorator->generateDescription(Sactivity),731:> D Api74> D Config75D DTO76> O Filters77D Jobs78> C ProspectSearchStrategy79// Only if they are creating a fresh engagement should we update the times, otherwise it will causeif (! $activity->hasCrmProviderIdO) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime()) €Smetadata['startTime'] = $decorator->formatStartTime(Sactivity):Smetadata[ 'endTime'] = $decorator->formatEndTime($activity);> D ServiceTraits80© DataClient.php81$metadata['title'] = $decorator->generateTitle($activity);© DecorateActivity.php82© LocalSearch.php83© LocalSearchinterface.php84field for someA DamntaCaarch nhn// For now, this is just a "meetingOutcome"D211-212— 213|214215216217218219220-221222223224225226= 227— 228229230231232233 V234customers.Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial,I on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities81:51UTF-8Co 4 spaces...
|
NULL
|
-1240337411389915602
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vlhl100% (C47HandleHubspotRateLimitTestv8• Thu 14 May 17:27:44* :QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php= custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.php() WriteCrmTrait.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php18.••© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© ClosedDealStagesService.pt19C DealFieldsService.php55© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php62© HubspotClientinterface.php© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): Activity'active' = true,'ownerId'= Sthis->profile->getCrmProviderIdO,'timestamp' => $decorator->formatStartTime($activity),'type' => 'MEETING',88 ×6 л606163© HubspotTokenManager.php64]:© PayloadBuilder.php65© RemoteCrmObjectManipulat66ResponseNormalize.php67if ($activity->hasActivityType() && $this->matchesCrmType($activity->getActivityType())){$engagement['activityType'] = $activity->getActivityType()->getName();© Service.php68© SyncFieldAction.php69© SyncRelatedActivityManage70© WebhookSyncBatchProcess71v D IntegrationApp72> [J Accessors$metadata = ['meetingOutcome' => $decorator->convertMeetingOutcome(Sactivity),'internalMeetingNotes'= $decorator->generateDescription(Sactivity),731:> D Api74> D Config75D DTO76> O Filters77D Jobs78> C ProspectSearchStrategy79// Only if they are creating a fresh engagement should we update the times, otherwise it will causeif (! $activity->hasCrmProviderIdO) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime()) €Smetadata['startTime'] = $decorator->formatStartTime(Sactivity):Smetadata[ 'endTime'] = $decorator->formatEndTime($activity);> D ServiceTraits80© DataClient.php81$metadata['title'] = $decorator->generateTitle($activity);© DecorateActivity.php82© LocalSearch.php83© LocalSearchinterface.php84field for someA DamntaCaarch nhn// For now, this is just a "meetingOutcome"D211-212— 213|214215216217218219220-221222223224225226= 227— 228229230231232233 V234customers.Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial,I on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities81:51UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45261
|
1623
|
10
|
2026-05-14T14:27:47.498853+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768867498_m1.jpg...
|
PhpStorm
|
faVsco.js – WriteCrmTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% (C47•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTestv8• Thu 14 May 17:27:47* :QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php= custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.php() WriteCrmTrait.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php18© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© ClosedDealStagesService.pt19C DealFieldsService.php55© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php62© HubspotClientinterface.php© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): Activity'active' = true,'ownerId'= Sthis->profile->getCrmProviderIdO,'timestamp' => $decorator->formatStartTime($activity),'type' => 'MEETING',88 ×6 л606163© HubspotTokenManager.php64]:© PayloadBuilder.php65© RemoteCrmObjectManipulatResponseNormalize.php6667if ($activity->hasActivityType() && $this->matchesChmType($activity->getActivityType())) {$engagement['activityType'] = $activity->getActivityType() ->getName();© Service.php68© SyncFieldAction.php69© SyncRelatedActivityManage70© WebhookSyncBatchProcess71v D IntegrationApp72> [J Accessors$metadata = ['meetingOutcome' => $decorator->convertMeetingOutcome($activity),'internalMeetingNotes'= $decorator->generateDescription(Sactivity),731:> D Api74> D Config75D DTO76> O Filters77D Jobs780 ProspectSearchStrategy79// Only if they are creating a fresh engagement should we update the times, otherwise it willcauseif (! $activity->hasCrmProviderIdO) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime()) €Smetadata['startTime'] = $decorator->formatStartTime(Sactivity):Smetadata[ 'endTime'] = $decorator->formatEndTime($activity);> D ServiceTraits80© DataClient.php81Smetadata['title'] = $decorator->generateTitle($activity):© DecorateActivity.php82© LocalSearch.php83© LocalSearchinterface.php84A DamntaCaarch nhn// For now, this is just a "meetingOutcome"field for somecustomers.Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]D211-212— 213|214215216217218219220-221222223224225226= 227— 228229230— 231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial,on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities66:60UTF-8Co 4 spaces...
|
NULL
|
19990527998985743
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% (C47•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTestv8• Thu 14 May 17:27:47* :QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php= custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.php() WriteCrmTrait.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php18© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© ClosedDealStagesService.pt19C DealFieldsService.php55© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php62© HubspotClientinterface.php© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): Activity'active' = true,'ownerId'= Sthis->profile->getCrmProviderIdO,'timestamp' => $decorator->formatStartTime($activity),'type' => 'MEETING',88 ×6 л606163© HubspotTokenManager.php64]:© PayloadBuilder.php65© RemoteCrmObjectManipulatResponseNormalize.php6667if ($activity->hasActivityType() && $this->matchesChmType($activity->getActivityType())) {$engagement['activityType'] = $activity->getActivityType() ->getName();© Service.php68© SyncFieldAction.php69© SyncRelatedActivityManage70© WebhookSyncBatchProcess71v D IntegrationApp72> [J Accessors$metadata = ['meetingOutcome' => $decorator->convertMeetingOutcome($activity),'internalMeetingNotes'= $decorator->generateDescription(Sactivity),731:> D Api74> D Config75D DTO76> O Filters77D Jobs780 ProspectSearchStrategy79// Only if they are creating a fresh engagement should we update the times, otherwise it willcauseif (! $activity->hasCrmProviderIdO) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime()) €Smetadata['startTime'] = $decorator->formatStartTime(Sactivity):Smetadata[ 'endTime'] = $decorator->formatEndTime($activity);> D ServiceTraits80© DataClient.php81Smetadata['title'] = $decorator->generateTitle($activity):© DecorateActivity.php82© LocalSearch.php83© LocalSearchinterface.php84A DamntaCaarch nhn// For now, this is just a "meetingOutcome"field for somecustomers.Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]D211-212— 213|214215216217218219220-221222223224225226= 227— 228229230— 231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial,on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities66:60UTF-8Co 4 spaces...
|
45259
|
NULL
|
NULL
|
NULL
|
|
45262
|
1624
|
8
|
2026-05-14T14:27:48.944434+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768868944_m2.jpg...
|
PhpStorm
|
faVsco.js – WriteCrmTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mау 1/•21.40Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-5464364581231200547
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mау 1/•21.40Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45260
|
NULL
|
NULL
|
NULL
|
|
45264
|
1623
|
11
|
2026-05-14T14:27:51.377282+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768871377_m1.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvProjectvViewNavigate PhpStormFileEdit•FV faVsco.jsvProjectvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest100% (C478• Thu 14 May 17:27:50* :Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.logT SyncFieldsTrait.php() WriteCrmTrait.php> O Utils.> D WebhookDeleteCrmEntityTrait.php© AccountController.phpDeleteAccountJob.phpImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.phpSF [jiminny@localhost]© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.phpA HS_local [jiminny@localho:WT IntegrationAppTrait.php.env.staging18E.env© DetachActivityObject.php4 console [QAI PROD] X© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php4 console [PROD]© Client.php© ClosedDealStagesService.ptC DealFieldsService.php© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): ActivityA console (EU]© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php© HubspotTokenManager.php© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> D Api> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy> D ServiceTraits© DataClient.php ×6 лExtractSurround // E$metadata = ['meetingOutcome'=> $decorator->convertMeetingOutcome($activity),'internalMeetingNotes' => $decorator->generateDescription(Sactivity),// Only if they are creating a fresh engagement should we update the times, otherwise it willcauseif (! $activity->hasCrmProviderId()) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime)) {Smetadata['startTime'] = $decorator->formatStartTime(Sactivity);Smetadata[ 'endTime'] = $decorator->formatEndTime($activity);$metadata['title'] = $decorator->generateTitle($activity);// For now, this is just a "meetingOutcome"field for somecustomers.$metadata =array_merge(Smetadata, $this->fetchCustomFieldData(Sactivity, Field::0BJECT_TASK));return $this->upsertActivity(Sactivity,Sengagement, Smetadata);© DecorateActivity.php© LocalSearch.php2 usages© LocalSearchinterface.php90private function fetchCustomFieldData(Activity $activity, string $objectType): array{...D211-212— 213|-214215-216217218219220-221222223224225226=227— 228229230— 231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;team_feature:m opportunitie:m teams;1.id,CASEWHENidFROMsocial,on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivitiesA DamntaCaarch nhn106Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams67:41 (27 chars)UTF-8Co 4 spaces...
|
NULL
|
9088124837664002467
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvProjectvViewNavigate PhpStormFileEdit•FV faVsco.jsvProjectvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest100% (C478• Thu 14 May 17:27:50* :Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.logT SyncFieldsTrait.php() WriteCrmTrait.php> O Utils.> D WebhookDeleteCrmEntityTrait.php© AccountController.phpDeleteAccountJob.phpImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.phpSF [jiminny@localhost]© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.phpA HS_local [jiminny@localho:WT IntegrationAppTrait.php.env.staging18E.env© DetachActivityObject.php4 console [QAI PROD] X© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php4 console [PROD]© Client.php© ClosedDealStagesService.ptC DealFieldsService.php© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): ActivityA console (EU]© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php© HubspotTokenManager.php© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> D Api> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy> D ServiceTraits© DataClient.php ×6 лExtractSurround // E$metadata = ['meetingOutcome'=> $decorator->convertMeetingOutcome($activity),'internalMeetingNotes' => $decorator->generateDescription(Sactivity),// Only if they are creating a fresh engagement should we update the times, otherwise it willcauseif (! $activity->hasCrmProviderId()) {if (Sactivity->hasActualStartTime() && $activity->hasActualEndTime)) {Smetadata['startTime'] = $decorator->formatStartTime(Sactivity);Smetadata[ 'endTime'] = $decorator->formatEndTime($activity);$metadata['title'] = $decorator->generateTitle($activity);// For now, this is just a "meetingOutcome"field for somecustomers.$metadata =array_merge(Smetadata, $this->fetchCustomFieldData(Sactivity, Field::0BJECT_TASK));return $this->upsertActivity(Sactivity,Sengagement, Smetadata);© DecorateActivity.php© LocalSearch.php2 usages© LocalSearchinterface.php90private function fetchCustomFieldData(Activity $activity, string $objectType): array{...D211-212— 213|-214215-216217218219220-221222223224225226=227— 228229230— 231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;team_feature:m opportunitie:m teams;1.id,CASEWHENidFROMsocial,on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivitiesA DamntaCaarch nhn106Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams67:41 (27 chars)UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45263
|
1624
|
9
|
2026-05-14T14:27:56.239351+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768876239_m2.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"15","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"12","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Repositories\\ActivityMessageRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Crm\\DecorateActivity\\BaseDecorateActivity;\n\nclass DecorateActivity extends BaseDecorateActivity\n{\n public const string JIMINNY_MARKER = 'Jiminny Summary:';\n\n public function generateTitle(Activity $activity): ?string\n {\n if ($activity->hasTitle()) {\n $title = $activity->getTitle();\n } elseif ($activity->hasActivityType()) {\n $title = $activity->getActivityType()->getName();\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n public function convertMeetingOutcome(Activity $activity): ?string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_SCHEDULED:\n return 'SCHEDULED';\n case Activity::STATUS_CANCELLED:\n return 'CANCELED';\n case Activity::STATUS_COMPLETED:\n return 'COMPLETED';\n //case Activity::STATUS_NO_SHOW:\n // return 'NO_SHOW';\n default:\n return null;\n }\n }\n\n public function convertCallStatus(Activity $activity): string\n {\n switch ($activity->getStatus()) {\n case Activity::STATUS_NO_ANSWER:\n return 'NO_ANSWER';\n default:\n return 'COMPLETED';\n }\n }\n\n public function generateDescription(Activity $activity): ?string\n {\n if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {\n return $this->formatSmsDescription($activity);\n }\n\n $description = $this->baseDescription();\n\n if ($activity->hasTitle() && $activity->hasActivityType()) {\n $description .= $this->formatActivityType($activity->getActivityType()->getName());\n }\n\n if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n $description .= $this->formatSoftphoneDetails($activity);\n }\n\n $description .= $this->formatReasonOrPreview($activity);\n\n if ($activity->isTypeConference()) {\n $description .= $this->formatAttendeesList($activity);\n }\n\n return $description\n . $this->formatNotes($activity)\n . $this->formatMessages($activity)\n . $this->formatSummary($activity);\n }\n\n public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string\n {\n if (empty($existingCrmDescription)) {\n return $jiminnyDescription;\n }\n\n if (! $this->isJiminnyDescription($existingCrmDescription)) {\n return $existingCrmDescription . '<hr>' . $jiminnyDescription;\n }\n\n $existingSections = $this->parseHtmlSections($existingCrmDescription);\n $newSections = $this->parseHtmlSections($jiminnyDescription);\n\n return $this->mergeHtmlSections($newSections, $existingSections);\n }\n\n private function parseHtmlSections(string $html): array\n {\n $sections = [\n 'beforeJiminny' => '',\n 'header' => '',\n ];\n\n foreach (self::SECTION_HEADERS as $name) {\n $sections[$name] = '';\n }\n\n $headerStartPos = $this->findHeaderStartPosition($html);\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n\n if ($headerStartPos !== false && $headerStartPos > 0) {\n $sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));\n }\n\n if ($headerStartPos !== false) {\n $jiminnyStart = $headerStartPos;\n } elseif ($markerPos !== false) {\n $jiminnyStart = $markerPos;\n } else {\n $jiminnyStart = 0;\n }\n\n $firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);\n\n if ($firstSectionPos === false) {\n $sections['header'] = substr($html, $jiminnyStart);\n } else {\n $sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);\n }\n\n $sections['header'] = trim($sections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);\n }\n\n return $sections;\n }\n\n private function findHeaderStartPosition(string $html): int|false\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*<span[^>]*>\\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';\n\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {\n return $matches[0][1];\n }\n\n $markerPos = stripos($html, self::JIMINNY_MARKER);\n if ($markerPos === false) {\n return false;\n }\n\n $beforeMarker = substr($html, 0, $markerPos);\n $lastPTagPos = strrpos($beforeMarker, '<p');\n\n return $lastPTagPos !== false ? $lastPTagPos : $markerPos;\n }\n\n private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false\n {\n $firstPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($firstPos === false || $pos < $firstPos) {\n $firstPos = $pos;\n }\n }\n }\n\n return $firstPos;\n }\n\n private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string\n {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n\n if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n return '';\n }\n\n $headerMatch = $matches[0][0];\n $headerPos = $matches[0][1];\n $contentStart = $headerPos + strlen($headerMatch);\n\n $nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);\n\n if ($nextSectionPos === false) {\n $content = substr($html, $contentStart);\n } else {\n $content = substr($html, $contentStart, $nextSectionPos - $contentStart);\n }\n\n return trim($content);\n }\n\n private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false\n {\n $nextPos = false;\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $pattern = '/<p[^>]*>\\s*<strong[^>]*>\\s*' . preg_quote($sectionName, '/') . '\\s*<\\/strong>\\s*<\\/p>/i';\n if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {\n $pos = $matches[0][1];\n if ($nextPos === false || $pos < $nextPos) {\n $nextPos = $pos;\n }\n }\n }\n\n return $nextPos;\n }\n\n private function mergeHtmlSections(array $newSections, array $existingSections): string\n {\n $result = '';\n\n if (! empty($existingSections['beforeJiminny'])) {\n $result .= $existingSections['beforeJiminny'];\n }\n\n $result .= $this->wrapHeader($newSections['header']);\n\n foreach (self::SECTION_HEADERS as $sectionName) {\n $existingContent = $existingSections[$sectionName] ?? '';\n $newContent = $newSections[$sectionName] ?? '';\n\n $content = ! empty($existingContent) ? $existingContent : $newContent;\n\n if (! empty($content)) {\n $result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;\n }\n }\n\n return $result;\n }\n\n private function wrapHeader(string $header): string\n {\n $header = trim($header);\n\n if (str_starts_with($header, '<p>')) {\n return $header;\n }\n\n if (str_starts_with($header, self::JIMINNY_MARKER)) {\n return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));\n }\n\n return $header;\n }\n\n private function baseDescription(): string\n {\n return sprintf(\n '<p><strong><span style=\"font-size: 15px; line-height: 30px;\">%s</span></strong></p>',\n 'Jiminny Summary:'\n );\n }\n\n private function formatSoftphoneDetails(Activity $activity): string\n {\n $isOutbound = $activity->isTypeSoftPhone();\n $isInbound = $activity->isTypeSoftphoneInbound();\n\n if (! $isOutbound && ! $isInbound) {\n return '';\n }\n\n $output = $this->formatTitle($activity->getTitle());\n $output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));\n\n $phone = $isOutbound\n ? $activity->to?->phone_number\n : $activity->from?->phone_number;\n\n if ($phone) {\n $output .= $isOutbound\n ? $this->formatDialedNumber($phone)\n : $this->formatCallerNumber($phone);\n }\n\n return $output . '<p></p>';\n }\n\n private function formatReasonOrPreview(Activity $activity): string\n {\n if ($activity->hasReasonCodeBotKicked()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span></p>';\n }\n\n if ($activity->hasReasonCodeNotCompliant()) {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span></p>';\n }\n\n return $this->formatPreviewUrl($activity);\n }\n\n\n public function formatStartTime(Activity $activity): int\n {\n return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatEndTime(Activity $activity): int\n {\n return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCreatedAt(Activity $activity): int\n {\n return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;\n }\n\n public function formatCallToParticipant(Activity $activity): ?string\n {\n $callToParticipant = $activity->getToParticipant()?->getPhoneNumber();\n if ($callToParticipant && $activity->hasContact()) {\n return $activity->getContact()->getName() . ' ' . $callToParticipant;\n }\n\n return null;\n }\n\n private function formatActivityType(string $activityType): string\n {\n return '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">' . $activityType . '</span></strong></p>';\n }\n\n private function formatTitle(?string $title): string\n {\n return $title ? '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $title . '</span></p>' : '';\n }\n\n private function formatCallDuration(string $duration): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: ' . $duration . '</span></p>';\n }\n\n private function formatDialedNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatCallerNumber(string $phoneNumber): string\n {\n return '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: ' . $phoneNumber . '</span></p>';\n }\n\n private function formatAttendeesList(Activity $activity): string\n {\n $attendeesList = '<p><strong>Attendees</strong></p><ul>';\n\n $participantsRepository = app(ParticipantRepository::class);\n // Only include participants that joined.\n $participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->hasName()) {\n $attendee .= $participant->getName();\n if ($participant->hasPhoneNumber()) {\n $attendee .= ' (' . $participant->getPhoneNumber() . ')';\n } elseif ($participant->hasEmailAddress()) {\n $attendee .= ' (' . $participant->getEmailAddress() . ')';\n }\n } else {\n $attendee .= $participant->getPhoneNumber();\n }\n\n if ($participant->isCoach()) {\n $attendee .= ' <strong>coach</strong>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $attendeesList .= $attendee . '</li>';\n }\n\n return $attendeesList . '</ul>';\n }\n\n private function formatPreviewUrl(Activity $activity): string\n {\n $description = '';\n $team = $activity->getUser()->getTeam();\n\n if ($activity->canReviewActivity()) {\n $playbackUrl = $team->getPartner()->getPlaybackUrl($activity);\n $description .= '<p><span style=\"font-size: 13.3333px; line-height: 16px;\"><a href=\"'\n . $playbackUrl\n . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>';\n }\n\n return $description;\n }\n\n private function formatNotes(Activity $activity): string\n {\n $description = '';\n if ($activity->getNotes()->isEmpty()) {\n return $description;\n }\n\n $description .= '<p><strong>Notes</strong></p>';\n foreach ($activity->getNotes() as $note) {\n $time = ($note->getTime() > 3600)\n ? gmdate('H:i:s', (int) $note->getTime())\n : gmdate('i:s', (int) $note->getTime());\n\n $description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';\n }\n\n return $description . '</p>';\n }\n\n private function formatMessages(Activity $activity): string\n {\n $description = '';\n $messageRepository = app(ActivityMessageRepository::class);\n\n // Get all private messages.\n $privateMessages = $messageRepository->getPrivateMessages($activity);\n if ($privateMessages->isNotEmpty()) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n $description .= $this->getMessagesAsString($privateMessages);\n $description .= '</p>';\n }\n\n // Get all public messages\n $publicMessages = $messageRepository->getPublicMessages($activity);\n if ($publicMessages->isNotEmpty()) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n $description .= $this->getMessagesAsString($publicMessages);\n $description .= '</p>';\n }\n\n return $description;\n }\n\n private function getMessagesAsString(Collection $messages): string\n {\n $description = '';\n\n /** @var Activity\\Message $message */\n foreach ($messages as $message) {\n $description .= '<p>' . $message->participant->getName()\n . ': ' . $message->getAttribute('message') . '</p>';\n }\n\n return $description;\n }\n\n private function formatSummary(Activity $activity): string\n {\n $description = '';\n if ($activity->getSummary() !== null) {\n $description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';\n }\n\n return $description;\n }\n\n private function formatSmsDescription(Activity $activity): string\n {\n // Use Rich-text formatting.\n $description = '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>' . $activity->getTitle() . '</strong></span></p>';\n $description .= '<p><span style=\"font-size: 16px; line-height: 19.2px;\">' . $activity->getDescription() . '</span></p>';\n\n return $description;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.28224733,"top":1.0,"width":0.024268618,"height":-0.04788506},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
3720258616318464950
|
9001456016336028185
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
1
2
15
12
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Illuminate\Support\Collection;
use Jiminny\Models\Activity;
use Jiminny\Repositories\ActivityMessageRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Crm\DecorateActivity\BaseDecorateActivity;
class DecorateActivity extends BaseDecorateActivity
{
public const string JIMINNY_MARKER = 'Jiminny Summary:';
public function generateTitle(Activity $activity): ?string
{
if ($activity->hasTitle()) {
$title = $activity->getTitle();
} elseif ($activity->hasActivityType()) {
$title = $activity->getActivityType()->getName();
} else {
$title = 'Conference Call';
}
return $title;
}
public function convertMeetingOutcome(Activity $activity): ?string
{
switch ($activity->getStatus()) {
case Activity::STATUS_SCHEDULED:
return 'SCHEDULED';
case Activity::STATUS_CANCELLED:
return 'CANCELED';
case Activity::STATUS_COMPLETED:
return 'COMPLETED';
//case Activity::STATUS_NO_SHOW:
// return 'NO_SHOW';
default:
return null;
}
}
public function convertCallStatus(Activity $activity): string
{
switch ($activity->getStatus()) {
case Activity::STATUS_NO_ANSWER:
return 'NO_ANSWER';
default:
return 'COMPLETED';
}
}
public function generateDescription(Activity $activity): ?string
{
if (in_array($activity->getType(), [Activity::TYPE_SMS_INBOUND, Activity::TYPE_SMS_OUTBOUND], true)) {
return $this->formatSmsDescription($activity);
}
$description = $this->baseDescription();
if ($activity->hasTitle() && $activity->hasActivityType()) {
$description .= $this->formatActivityType($activity->getActivityType()->getName());
}
if ($activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
$description .= $this->formatSoftphoneDetails($activity);
}
$description .= $this->formatReasonOrPreview($activity);
if ($activity->isTypeConference()) {
$description .= $this->formatAttendeesList($activity);
}
return $description
. $this->formatNotes($activity)
. $this->formatMessages($activity)
. $this->formatSummary($activity);
}
public function mergeDescriptions(string $jiminnyDescription, ?string $existingCrmDescription): string
{
if (empty($existingCrmDescription)) {
return $jiminnyDescription;
}
if (! $this->isJiminnyDescription($existingCrmDescription)) {
return $existingCrmDescription . '<hr>' . $jiminnyDescription;
}
$existingSections = $this->parseHtmlSections($existingCrmDescription);
$newSections = $this->parseHtmlSections($jiminnyDescription);
return $this->mergeHtmlSections($newSections, $existingSections);
}
private function parseHtmlSections(string $html): array
{
$sections = [
'beforeJiminny' => '',
'header' => '',
];
foreach (self::SECTION_HEADERS as $name) {
$sections[$name] = '';
}
$headerStartPos = $this->findHeaderStartPosition($html);
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($headerStartPos !== false && $headerStartPos > 0) {
$sections['beforeJiminny'] = trim(substr($html, 0, $headerStartPos));
}
if ($headerStartPos !== false) {
$jiminnyStart = $headerStartPos;
} elseif ($markerPos !== false) {
$jiminnyStart = $markerPos;
} else {
$jiminnyStart = 0;
}
$firstSectionPos = $this->findFirstHtmlSectionPosition($html, $jiminnyStart);
if ($firstSectionPos === false) {
$sections['header'] = substr($html, $jiminnyStart);
} else {
$sections['header'] = substr($html, $jiminnyStart, $firstSectionPos - $jiminnyStart);
}
$sections['header'] = trim($sections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$sections[$sectionName] = $this->extractHtmlSectionContent($html, $sectionName, $jiminnyStart);
}
return $sections;
}
private function findHeaderStartPosition(string $html): int|false
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*<span[^>]*>\s*' . preg_quote(self::JIMINNY_MARKER, '/') . '/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
return $matches[0][1];
}
$markerPos = stripos($html, self::JIMINNY_MARKER);
if ($markerPos === false) {
return false;
}
$beforeMarker = substr($html, 0, $markerPos);
$lastPTagPos = strrpos($beforeMarker, '<p');
return $lastPTagPos !== false ? $lastPTagPos : $markerPos;
}
private function findFirstHtmlSectionPosition(string $html, int $afterPosition = 0): int|false
{
$firstPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($firstPos === false || $pos < $firstPos) {
$firstPos = $pos;
}
}
}
return $firstPos;
}
private function extractHtmlSectionContent(string $html, string $sectionName, int $afterPosition = 0): string
{
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (! preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
return '';
}
$headerMatch = $matches[0][0];
$headerPos = $matches[0][1];
$contentStart = $headerPos + strlen($headerMatch);
$nextSectionPos = $this->findNextHtmlSectionPosition($html, $contentStart);
if ($nextSectionPos === false) {
$content = substr($html, $contentStart);
} else {
$content = substr($html, $contentStart, $nextSectionPos - $contentStart);
}
return trim($content);
}
private function findNextHtmlSectionPosition(string $html, int $afterPosition): int|false
{
$nextPos = false;
foreach (self::SECTION_HEADERS as $sectionName) {
$pattern = '/<p[^>]*>\s*<strong[^>]*>\s*' . preg_quote($sectionName, '/') . '\s*<\/strong>\s*<\/p>/i';
if (preg_match($pattern, $html, $matches, PREG_OFFSET_CAPTURE, $afterPosition)) {
$pos = $matches[0][1];
if ($nextPos === false || $pos < $nextPos) {
$nextPos = $pos;
}
}
}
return $nextPos;
}
private function mergeHtmlSections(array $newSections, array $existingSections): string
{
$result = '';
if (! empty($existingSections['beforeJiminny'])) {
$result .= $existingSections['beforeJiminny'];
}
$result .= $this->wrapHeader($newSections['header']);
foreach (self::SECTION_HEADERS as $sectionName) {
$existingContent = $existingSections[$sectionName] ?? '';
$newContent = $newSections[$sectionName] ?? '';
$content = ! empty($existingContent) ? $existingContent : $newContent;
if (! empty($content)) {
$result .= '<p><strong>' . $sectionName . '</strong></p>' . $content;
}
}
return $result;
}
private function wrapHeader(string $header): string
{
$header = trim($header);
if (str_starts_with($header, '<p>')) {
return $header;
}
if (str_starts_with($header, self::JIMINNY_MARKER)) {
return $this->baseDescription() . substr($header, strlen(self::JIMINNY_MARKER));
}
return $header;
}
private function baseDescription(): string
{
return sprintf(
'<p><strong><span style="font-size: 15px; line-height: 30px;">%s</span></strong></p>',
'Jiminny Summary:'
);
}
private function formatSoftphoneDetails(Activity $activity): string
{
$isOutbound = $activity->isTypeSoftPhone();
$isInbound = $activity->isTypeSoftphoneInbound();
if (! $isOutbound && ! $isInbound) {
return '';
}
$output = $this->formatTitle($activity->getTitle());
$output .= $this->formatCallDuration($activity->getAttribute('duration_for_humans'));
$phone = $isOutbound
? $activity->to?->phone_number
: $activity->from?->phone_number;
if ($phone) {
$output .= $isOutbound
? $this->formatDialedNumber($phone)
: $this->formatCallerNumber($phone);
}
return $output . '<p></p>';
}
private function formatReasonOrPreview(Activity $activity): string
{
if ($activity->hasReasonCodeBotKicked()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker removed from this meeting'
. '</span></p>';
}
if ($activity->hasReasonCodeNotCompliant()) {
return '<p><span style="font-size: 13.3333px; line-height: 16px;">'
. 'Notetaker did not join due to recording consent not being provided by attendees'
. '</span></p>';
}
return $this->formatPreviewUrl($activity);
}
public function formatStartTime(Activity $activity): int
{
return $activity->getActualStartTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatEndTime(Activity $activity): int
{
return $activity->getActualEndTime()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCreatedAt(Activity $activity): int
{
return $activity->getCreatedAt()->tz($activity->getUser()->timezone)->getTimestamp() * 1000;
}
public function formatCallToParticipant(Activity $activity): ?string
{
$callToParticipant = $activity->getToParticipant()?->getPhoneNumber();
if ($callToParticipant && $activity->hasContact()) {
return $activity->getContact()->getName() . ' ' . $callToParticipant;
}
return null;
}
private function formatActivityType(string $activityType): string
{
return '<p><strong><span style="font-size: 18.6667px; line-height: 22.4px;">' . $activityType . '</span></strong></p>';
}
private function formatTitle(?string $title): string
{
return $title ? '<p><span style="font-size: 16px; line-height: 19.2px;">' . $title . '</span></p>' : '';
}
private function formatCallDuration(string $duration): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: ' . $duration . '</span></p>';
}
private function formatDialedNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: ' . $phoneNumber . '</span></p>';
}
private function formatCallerNumber(string $phoneNumber): string
{
return '<p><span style="font-size: 13.3333px; line-height: 16px;">Caller: ' . $phoneNumber . '</span></p>';
}
private function formatAttendeesList(Activity $activity): string
{
$attendeesList = '<p><strong>Attendees</strong></p><ul>';
$participantsRepository = app(ParticipantRepository::class);
// Only include participants that joined.
$participants = $participantsRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
$attendee = '<li>';
if ($participant->hasName()) {
$attendee .= $participant->getName();
if ($participant->hasPhoneNumber()) {
$attendee .= ' (' . $participant->getPhoneNumber() . ')';
} elseif ($participant->hasEmailAddress()) {
$attendee .= ' (' . $participant->getEmailAddress() . ')';
}
} else {
$attendee .= $participant->getPhoneNumber();
}
if ($participant->isCoach()) {
$attendee .= ' <strong>coach</strong>';
}
if ($participant->getTitle()) {
$attendee .= ', ' . $participant->getTitle();
}
$attendeesList .= $attendee . '</li>';
}
return $attendeesList . '</ul>';
}
private function formatPreviewUrl(Activity $activity): string
{
$description = '';
$team = $activity->getUser()->getTeam();
if ($activity->canReviewActivity()) {
$playbackUrl = $team->getPartner()->getPlaybackUrl($activity);
$description .= '<p><span style="font-size: 13.3333px; line-height: 16px;"><a href="'
. $playbackUrl
. '" target="_blank">Review in Jiminny</a> ▶️</span></p>';
}
return $description;
}
private function formatNotes(Activity $activity): string
{
$description = '';
if ($activity->getNotes()->isEmpty()) {
return $description;
}
$description .= '<p><strong>Notes</strong></p>';
foreach ($activity->getNotes() as $note) {
$time = ($note->getTime() > 3600)
? gmdate('H:i:s', (int) $note->getTime())
: gmdate('i:s', (int) $note->getTime());
$description .= '<p>' . $time . ' ' . $note->getNote() . '</p>';
}
return $description . '</p>';
}
private function formatMessages(Activity $activity): string
{
$description = '';
$messageRepository = app(ActivityMessageRepository::class);
// Get all private messages.
$privateMessages = $messageRepository->getPrivateMessages($activity);
if ($privateMessages->isNotEmpty()) {
$description .= '<p><strong>Coaching Chat</strong></p>';
$description .= $this->getMessagesAsString($privateMessages);
$description .= '</p>';
}
// Get all public messages
$publicMessages = $messageRepository->getPublicMessages($activity);
if ($publicMessages->isNotEmpty()) {
$description .= '<p><strong>Customer Chat</strong></p>';
$description .= $this->getMessagesAsString($publicMessages);
$description .= '</p>';
}
return $description;
}
private function getMessagesAsString(Collection $messages): string
{
$description = '';
/** @var Activity\Message $message */
foreach ($messages as $message) {
$description .= '<p>' . $message->participant->getName()
. ': ' . $message->getAttribute('message') . '</p>';
}
return $description;
}
private function formatSummary(Activity $activity): string
{
$description = '';
if ($activity->getSummary() !== null) {
$description .= '<p><strong>Summary</strong></p><p>' . nl2br($activity->getSummary()) . '</p><p></p>';
}
return $description;
}
private function formatSmsDescription(Activity $activity): string
{
// Use Rich-text formatting.
$description = '<p><span style="font-size: 16px; line-height: 19.2px;"><strong>' . $activity->getTitle() . '</strong></span></p>';
$description .= '<p><span style="font-size: 16px; line-height: 19.2px;">' . $activity->getDescription() . '</span></p>';
return $description;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45266
|
1624
|
10
|
2026-05-14T14:27:57.176559+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768877176_m2.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 May 1/.2/:06Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
4406730710463997191
|
NULL
|
click
|
ocr
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.55 GB availabld• Inu 14 May 1/.2/:06Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45263
|
NULL
|
NULL
|
NULL
|
|
45265
|
1623
|
12
|
2026-05-14T14:27:57.220305+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768877220_m1.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLara PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :Projectv8• Thu 14 May 17:27:57Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny|Services\Crm\Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> Api|> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C181920|2122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?stringif ($activity->hasTitleO) {$title = $activity->getTitle();} elseif ($activity->hasActivityTypeO)) {$title = $activity->getActivityType()->getName();} else {$title = 'Conference Call':return $title;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.phpD2112122132147215216— 217-218-— 219220221222— 223|224225226— 227228— 229_230231232233 V23455A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities17:21UTF-8Co 4 spaces...
|
NULL
|
8019392810880732668
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLara PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :Projectv8• Thu 14 May 17:27:57Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny|Services\Crm\Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> Api|> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C181920|2122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?stringif ($activity->hasTitleO) {$title = $activity->getTitle();} elseif ($activity->hasActivityTypeO)) {$title = $activity->getActivityType()->getName();} else {$title = 'Conference Call':return $title;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.phpD2112122132147215216— 217-218-— 219220221222— 223|224225226— 227228— 229_230231232233 V23455A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities17:21UTF-8Co 4 spaces...
|
45264
|
NULL
|
NULL
|
NULL
|
|
45267
|
1623
|
13
|
2026-05-14T14:27:58.752613+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768878752_m1.jpg...
|
PhpStorm
|
faVsco.js – DecorateActivity.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLara PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :8• Thu 14 May 17:27:58QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny|Services\Crm\Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> Api|> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C1819202122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?string{if ($activity->hasTitleO)) {$title = $activity->getTitle();} elseif ($activity->hasActivityTypeO)) {$title = $activity->getActivityType() ->getName();} else {$title = 'Conference Call':return $title;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.php55A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D211212213214I215— 216-—217-218-— 219220221222— 223224225226— 227228— 229|_230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities20:37UTF-8Co 4 spaces...
|
NULL
|
-3547744504747755740
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLara PhpStormFileEdit•FV faVsco.jsvViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% (C47#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv* :8• Thu 14 May 17:27:58QProjectv© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.logT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpT SyncFieldsTrait.phpT WriteCrmTrait.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php X> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.php© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© Client.php© HandleHubspotRateLimit.php© ClosedDealStagesService.ptnamespace Jiminny|Services\Crm\Hubspot;01 A2 A15 X12 ^C DealFieldsService.php© DecorateActivity.phpuse© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php121314class DecorateActivity extends BaseDecorateActivity© HubspotTokenManager.php5 usages© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> Api|> D ConfigD DTOD FiltersD Jobs0 ProspectSearchStrategy• Service Traits© DataClient.php15 C1617 C1819202122232425262728293045public const string JIMINNY_MARKER = 'Jiminny Summary:';public function generateTitle(Activity $activity): ?string{if ($activity->hasTitleO)) {$title = $activity->getTitle();} elseif ($activity->hasActivityTypeO)) {$title = $activity->getActivityType() ->getName();} else {$title = 'Conference Call':return $title;public function convertMeetingOutcome(Activity Sactivity): ?string{...}© DecorateActivity.php2 usages© LocalSearch.php46public function convertCallStatus(Activity $activity): string{...}© LocalSearchinterface.php55A DamntaCaarch nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D211212213214I215— 216-—217-218-— 219220221222— 223224225226— 227228— 229|_230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities20:37UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45268
|
1623
|
14
|
2026-05-14T14:28:04.643028+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768884643_m1.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vabl100% (C47HandleHubspotRateLimitTest* :8• Thu 14 May 17:28:04QProjectv© ReportController.php© AutomatedReportGenerated.php=custom.logTrackAutomatedReportGeneratedEvent.phpPlaybackController.phpT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.logT SyncFieldsTrait.php() WriteCrmTrait.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.phpSF [jiminny@localhost]> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.phpA HS_local [jiminny@localho:W> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php4 console [QAI PROD] X18© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.php XMatchActivityCrmData.phpClient.phpHubspotPaginationService.php4 console [PROD]© Client.php© ClosedDealStagesService.ptC DealFieldsService.php1955© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): ActivityA console (EU]88 ×6 л© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php© HubspotTokenManager.php© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> D Api> D ConfigD DTO }Smetadata['title'] = Sdecorator-›generateTitle(Sactivity);}-D Filters2 usagesD Jobs0 ProspectSearchStrategy> D ServiceTraits© DataClient.php© DecorateActivity.php© LocalSearch.php90106107108109110private function fetchCustomFieldData(Activity $activity, string $objectType): array{..}/*** @throws HubspotException* @throws BadRequest*/© LocalSearchinterface.php3 usagesD211// Only if they are creating a fresh engagement should we update the times, otherwise it will causea_ 212if (! Sactivity->hasCrmProviderIdO) {— 213|if (Sactivity->hasActualStartTime() && Sactivity->hasActualEndTime()) f214Smetadata[ 'startTime'] = $decorator->formatStartTime(Sactivity);215$metadata['endTime'] = $decorator->formatEndTime($activity): = 227— 228229230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:// For now, this is just a "meetingOutcome" field for some customers.$metadata = array_merge($metadata, $this->fetchCustomFieldData(Sactivity, Field::0BJECT_TASK));m teams;return $this->upsertActivity(Sactivity, $engagement, $metadata);1.id, CASEWHENidFROMsocial,1 on u.id= sa.:1..n<->1: on t.Lid= 1052 andIMaccounts wheiactivitiesA DamntaCaarch nhn111private function uDsertActivitv(Activitv Sactivitv. arrav Senaadement. arrav Smetadata): Activitví...}Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams81:54UTF-8Co 4 spaces...
|
NULL
|
-3632303425739499902
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vabl100% (C47HandleHubspotRateLimitTest* :8• Thu 14 May 17:28:04QProjectv© ReportController.php© AutomatedReportGenerated.php=custom.logTrackAutomatedReportGeneratedEvent.phpPlaybackController.phpT SyncCrmEntitiesTrait.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.logT SyncFieldsTrait.php() WriteCrmTrait.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.phpSF [jiminny@localhost]> O Utils.© Service.phpT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.phpCrmHelperRepository.phpA HS_local [jiminny@localho:W> D Webhook© AccountController.phpT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.php4 console [QAI PROD] X18© BatchSyncCollector.php© BatchSyncRedisService.phpRematchActivityOnCrmObjectDetach.php XMatchActivityCrmData.phpClient.phpHubspotPaginationService.php4 console [PROD]© Client.php© ClosedDealStagesService.ptC DealFieldsService.php1955© HandleHubspotRateLimit.phptrait WriteCrmTraitprivate function buildConferencePayload(Activity $activity): ActivityA console (EU]88 ×6 л© DecorateActivity.php© FieldDefinitions.php© FieldTypeConverter.php© HubspotClientinterface.php© HubspotTokenManager.php© PayloadBuilder.php© RemoteCrmObjectManipulatResponseNormalize.php© Service.php© SyncFieldAction.php© SyncRelatedActivityManage© WebhookSyncBatchProcessv D IntegrationApp> [J Accessors> D Api> D ConfigD DTO }Smetadata['title'] = Sdecorator-›generateTitle(Sactivity);}-D Filters2 usagesD Jobs0 ProspectSearchStrategy> D ServiceTraits© DataClient.php© DecorateActivity.php© LocalSearch.php90106107108109110private function fetchCustomFieldData(Activity $activity, string $objectType): array{..}/*** @throws HubspotException* @throws BadRequest*/© LocalSearchinterface.php3 usagesD211// Only if they are creating a fresh engagement should we update the times, otherwise it will causea_ 212if (! Sactivity->hasCrmProviderIdO) {— 213|if (Sactivity->hasActualStartTime() && Sactivity->hasActualEndTime()) f214Smetadata[ 'startTime'] = $decorator->formatStartTime(Sactivity);215$metadata['endTime'] = $decorator->formatEndTime($activity): = 227— 228229230231232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:// For now, this is just a "meetingOutcome" field for some customers.$metadata = array_merge($metadata, $this->fetchCustomFieldData(Sactivity, Field::0BJECT_TASK));m teams;return $this->upsertActivity(Sactivity, $engagement, $metadata);1.id, CASEWHENidFROMsocial,1 on u.id= sa.:1..n<->1: on t.Lid= 1052 andIMaccounts wheiactivitiesA DamntaCaarch nhn111private function uDsertActivitv(Activitv Sactivitv. arrav Senaadement. arrav Smetadata): Activitví...}Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams81:54UTF-8Co 4 spaces...
|
45267
|
NULL
|
NULL
|
NULL
|
|
45269
|
1624
|
11
|
2026-05-14T14:28:04.648636+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768884648_m2.jpg...
|
PhpStorm
|
faVsco.js – Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterday at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Yesterday at 13:21Yesterday at 13.20Yesterdav at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterday at 13:15resterday at 13-10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yesterday at 13:09Yesterday at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KBMPEG-4 movie6 KB12 Kb9 KBIMPEG-4 movieMPEG-4 movie7 KB8 KBMPEG-4 movie37 K:10 KBMPEG-4 movie7 KBMPEG-4 movie9 KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 K:13 KBMPEG-4 movie9 KB18 KB|12 KBIMPEG-4 movieMPEG-4 movie10 KB16 KBMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie11 KEMPEG-4 movie11 KBMPEG-4 movie20 KB34 K:MPEG-4 movie10 KBMPEG-4 movie7 KB5KBMPEG-4 movie11 KPMPEG-4 movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:MPEG-4 movie88 KBMPEG-4 movie59 KB98 KBMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMPEG-4 movie7 KB12 KBMPEG-4 movie22 K:17 KBMPEG-4 movie19 KB32 K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-ywJo.ziPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfB Rovaix Famly Treo gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 May 1/.20.04Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-2819113653489521013
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterday at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Yesterday at 13:21Yesterday at 13.20Yesterdav at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterday at 13:15resterday at 13-10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yesterday at 13:09Yesterday at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KBMPEG-4 movie6 KB12 Kb9 KBIMPEG-4 movieMPEG-4 movie7 KB8 KBMPEG-4 movie37 K:10 KBMPEG-4 movie7 KBMPEG-4 movie9 KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 K:13 KBMPEG-4 movie9 KB18 KB|12 KBIMPEG-4 movieMPEG-4 movie10 KB16 KBMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie11 KEMPEG-4 movie11 KBMPEG-4 movie20 KB34 K:MPEG-4 movie10 KBMPEG-4 movie7 KB5KBMPEG-4 movie11 KPMPEG-4 movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:MPEG-4 movie88 KBMPEG-4 movie59 KB98 KBMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMPEG-4 movie7 KB12 KBMPEG-4 movie22 K:17 KBMPEG-4 movie19 KB32 K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-ywJo.ziPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfB Rovaix Famly Treo gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 May 1/.20.04Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45270
|
1623
|
15
|
2026-05-14T14:28:07.121354+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768887121_m1.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% CFV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :Project v8• Thu 14 May 17:28:06Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© PlaybackController.php=custom.log© DecorateActivity.php© UserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php©|ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© RemoteSearch.php© Service.php XT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.phpv C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata© HandleHubspotRateLimit.php80class Service extends BaseService implements> MigrationA11 A130 X3 X21 ^› Pipedrive86v O Salesforce87› D Fields88> D OpportunityMatcher89> OpportunitySyncStrategy90> D ProspectSearchStrategy91v D ServiceTraits92T BatchSyncTrait.php93D FollowupActivityTrait.php94& LogActivityTrait.php95T RecordManipulationsTrai96T SyncFieldsTrait.php97RemoteEntityManipulationInterface,FetchRelatedActivityInterface,SendSummaryToCrmInterface,MatchDomainByEmailInterface,SearchTaskInterface,LayoutManagementInterface,SettingsInterface,MatchCrmEntitiesInterface,RemoteEntityLookupInterface,Supports0bjectTypeParseInterface,RemoteNoteEntityManipulationInterface,VerifyTaskExistsInterface© Client.php98© DecorateActivity.php99T DeleteObjectsTrait.php100© FieldDefinitions.php101© PayloadBuilder.php102© Profile.php103© QueryBuilder.php104© QueryHandler.php105use ResolveCompanyNameByEmailTrait;use SyncFieldsTrait;use DeleteObjectsTrait;use RecordManipulationsTrait;use ServiceTraits\BatchSyncTrait;use FollowupActivityTrait;use LogActivityTrait;© Querylterator.php106© QueryResults.php107© Service.php108© SyncBatchRedisService.php109D Traits110C. Raceflient nhn111/**** @var int*/* Note Body Limit for the Old Note-Taking ToolWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]Go jiminny08A1A3 X4 ^ V211m migrations oi212— 213=214215216m teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wi217218219220m features;m team_feature:m opportunitie:221222m teams;2232241.id, CASEWHEN225226— 227-228229=230idFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 and231E232= 233 VIMaccounts wheiactivities— 23484:40UTF-8C 4 spaces...
|
NULL
|
-485834973145708984
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% CFV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :Project v8• Thu 14 May 17:28:06Q© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© PlaybackController.php=custom.log© DecorateActivity.php© UserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php© DeleteCrmEntityTrait.phpDeleteAccountJob.php©|ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© RemoteSearch.php© Service.php XT LogActivityTrait.php© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php=.env.staging18E.env© DetachActivityObject.phpv C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata© HandleHubspotRateLimit.php80class Service extends BaseService implements> MigrationA11 A130 X3 X21 ^› Pipedrive86v O Salesforce87› D Fields88> D OpportunityMatcher89> OpportunitySyncStrategy90> D ProspectSearchStrategy91v D ServiceTraits92T BatchSyncTrait.php93D FollowupActivityTrait.php94& LogActivityTrait.php95T RecordManipulationsTrai96T SyncFieldsTrait.php97RemoteEntityManipulationInterface,FetchRelatedActivityInterface,SendSummaryToCrmInterface,MatchDomainByEmailInterface,SearchTaskInterface,LayoutManagementInterface,SettingsInterface,MatchCrmEntitiesInterface,RemoteEntityLookupInterface,Supports0bjectTypeParseInterface,RemoteNoteEntityManipulationInterface,VerifyTaskExistsInterface© Client.php98© DecorateActivity.php99T DeleteObjectsTrait.php100© FieldDefinitions.php101© PayloadBuilder.php102© Profile.php103© QueryBuilder.php104© QueryHandler.php105use ResolveCompanyNameByEmailTrait;use SyncFieldsTrait;use DeleteObjectsTrait;use RecordManipulationsTrait;use ServiceTraits\BatchSyncTrait;use FollowupActivityTrait;use LogActivityTrait;© Querylterator.php106© QueryResults.php107© Service.php108© SyncBatchRedisService.php109D Traits110C. Raceflient nhn111/**** @var int*/* Note Body Limit for the Old Note-Taking ToolWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]Go jiminny08A1A3 X4 ^ V211m migrations oi212— 213=214215216m teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wi217218219220m features;m team_feature:m opportunitie:221222m teams;2232241.id, CASEWHEN225226— 227-228229=230idFROMsocial.on u.id= sa.:1..n<->1: on t.L_id = 1052 and231E232= 233 VIMaccounts wheiactivities— 23484:40UTF-8C 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45271
|
1624
|
12
|
2026-05-14T14:28:10.357930+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768890357_m2.jpg...
|
PhpStorm
|
faVsco.js – LogActivityTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
6
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Salesforce\ServiceTraits;
use Illuminate\Events\Dispatcher;
use Jiminny\Events\Activities\Crm\ActivityLeadConverted;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Feature\FeatureEnum;
use Jiminny\Models\Lead;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Services\Crm\Helpers\CrmHelperRepository;
use Jiminny\Services\Crm\Salesforce\DecorateActivity;
use Jiminny\Services\Crm\Salesforce\PayloadBuilder;
use Psr\Log\LoggerInterface;
trait LogActivityTrait
{
public ?Configuration $config;
public ?Profile $profile;
protected PayloadBuilder $payloadBuilder;
protected LoggerInterface $logger;
protected Dispatcher $eventDispatcher;
protected CrmHelperRepository $crmHelperRepository;
protected ?DecorateActivity $decorateActivity = null;
abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;
abstract public function matchesCrmType(PlaybookCategory $category): bool;
abstract public function syncLead(string $crmId): ?Lead;
abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;
abstract public function createRecord(string $objectType, array $data): string;
abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;
/**
* Save an activity, update CRM prospect objects
*
* Create or update a task or event (depending on most applicable playbook)
*/
public function saveActivity(Activity $activity): Activity
{
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
throw new InvalidArgumentException('Please configure a Playbook first.');
}
$this->logger->info('[Salesforce] Log activity', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
]);
$payload = [
'OwnerId' => $this->profile->getCrmProviderId(),
'Description' => $this->getActivityDecorator()->generateDescription($activity),
];
$payload += $this->buildSubjectPayload($activity, $playbook);
$payload += $this->buildProspectPayload($activity);
$crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK
? Field::OBJECT_TASK
: Field::OBJECT_EVENT;
$this->logger->info('[Salesforce] Log activity. Payload Prepared', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
'crm_object_type' => $crmObjectType,
'payload' => $payload,
]);
$this->saveCrmObject($crmObjectType, $activity, $payload);
return $activity;
}
private function buildSubjectPayload(Activity $activity, Playbook $playbook): array
{
if ($this->matchesCrmType($activity->getCategory())) {
/**
* If the activity playbook category name (i.e. activity type) matches a known activity type that exists
* in the CRM, then we set the activity type in the payload.
* Some activity types may be locally created. They shouldn't be sent to Salesforce.
*
* The resulting payload attribute will look like:
* `Type` => 'Cold Call'
*/
return [
/** ActivityFieldID => ActivityType */
$playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),
'Subject' => $this->getActivityDecorator()->generateTitle($activity),
];
}
/**
* Building of the title seems very inconsistent
* Subject here will be something like:
* "Local activity type: Activity Title"
*/
$subject = $activity->getCategory()->getName();
if ($activity->getTitle() !== null) {
$subject .= ': ' . $activity->getTitle();
}
return ['Subject' => $subject];
}
private function buildProspectPayload(Activity $activity): array
{
$payload = [];
if ($activity->getAccountId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'account_id' => $activity->getAccountId(),
'opportunity_id' => $activity->getOpportunityId(),
'contact_id' => $activity->getContactId(),
]);
$hasLinkFeature = $this->crmHelperRepository->hasFeature(
$activity,
FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS
);
if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())
|| (! $hasLinkFeature && $activity->getOpportunityId())
) {
$payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();
} else {
$payload['WhatId'] = $activity->getAccount()->getCrmProviderId();
}
}
if ($activity->getContactId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'contact_id' => $activity->getContactId(),
]);
$payload['WhoId'] = $activity->getContact()->getCrmProviderId();
} elseif ($activity->getLeadId()) {
$this->logger->info('[Salesforce] Activity has lead id', [
'activity_id' => $activity->getId(),
'lead_id' => $activity->getLeadId(),
]);
/**
* An activity may have:
* a) a contact | account | opportunity (or combinations)
* b) only a lead
* c) none of the above
*
* An activity should not have a lead, and another prospect object at the same time.
*
* This logical flow should not happen naturally, but as a fallback: if an activity has both
* a Lead and an Account, the account's WhatId takes precedence in the CRM payload.
* The lead association will be detached locally, but the account WhatId is preserved in Salesforce.
*/
$payload += $this->handleActivityLead($activity);
}
return $payload;
}
private function handleActivityLead(Activity $activity): array
{
$this->logger->info('[Salesforce] Activity sync lead', [
'activity_id' => $activity->getId(),
]);
/**
* Sync lead to pull fresh data. Leads change often,
* they may get 'converted', and we must handle the new state accordingly
*/
try {
$activityLead = $this->syncLead(
$activity->getLead()->getCrmProviderId()
);
} catch (HttpNotFoundException) {
$this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not found, maybe it's remotely deleted
*/
$this->resetLeadAssociation($activity);
return [];
}
if ($activityLead === null) {
$this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not loaded, for some reason. It may be remotely found, but locally deleted.
* Or an important Lead property may be missing, and it cannot be fully imported.
*/
$this->resetLeadAssociation($activity);
return [];
}
/**
* The lead is not converted, directly use it as WhoId and move on.
*/
if ($activityLead->getConvertedAt() === null) {
return [
'WhoId' => $activity->getLead()->getCrmProviderId(),
'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.
];
}
/**
* Task/Event payload properties for the CRM update
*/
$whoId = null;
$whatId = null;
/**
* Activity payload properties, that need to be updated.
*/
$convertedOpportunityId = null;
$convertedAccountId = null;
$convertedContactId = null;
$value = null;
/**
* If there is converted opportunity, it will update the activity stage.
* If there isn't an opportunity, a converted account/contact cannot have a stage id,
* so the activity shouldn't have a stage either.
*/
$stageId = null;
/**
* The lead is definitely converted.
* This means the lead may be associated with an opportunity, account, or contact.
* The converted lead itself must be detached from the activity,
* while the converted prospect objects must be associated instead,
* since they now represent the state of the deal.
*/
$activity->setLeadId(null);
/**
* CRM property "WhatId" can be either an Opportunity or an Account.
* For us a converted Opportunity has higher priority than an Account.
* An Opportunity carries more concrete data, including a reference to the Account record itself.
*/
if ($activityLead->hasOpportunity()) {
$convertedOpportunity = $activityLead->getOpportunity();
$convertedOpportunityId = $convertedOpportunity->getId();
$convertedAccountId = $convertedOpportunity->getAccountId();
$stageId = $convertedOpportunity->getStageId();
$value = $convertedOpportunity->getValue();
$whatId = $convertedOpportunity->getCrmProviderId();
}
if ($activityLead->hasAccount()) {
$convertedAccount = $activityLead->getAccount();
$convertedAccountId ??= $convertedAccount->getId();
$whatId ??= $convertedAccount->getCrmProviderId();
}
/**
* WhoId can only be a Contact or a Lead.
* Since we are detaching the Lead, it can only be a Contact for the current activity.
* It does not conflict with any other object.
*/
if ($activityLead->hasContact()) {
$convertedContact = $activityLead->getContact();
$convertedContactId = $convertedContact->getId();
$whoId = $convertedContact->getCrmProviderId();
}
$activity->setOpportunityId($convertedOpportunityId);
$activity->setAccountId($convertedAccountId);
$activity->setContactId($convertedContactId);
$activity->setStageId($stageId);
$activity->setValue($value);
$activity->save();
$this->eventDispatcher->dispatch(
new ActivityLeadConverted($activity, $activityLead)
);
$this->logger->info('[Salesforce] Lead is converted', [
'activity_id' => $activity->getId(),
'whoId' => $whoId,
'whatId' => $whatId,
]);
return [
'WhoId' => $whoId,
'WhatId' => $whatId,
];
}
private function saveCrmObject(string $objectType, Activity $activity, array $payload): void
{
/**
* Tasks and events have different payload structures,
* so we need to consider the type of the object we are sending to the CRM
*/
$specificPayload = $objectType === Field::OBJECT_TASK
? $this->payloadBuilder->buildTaskPayload($activity)
: $this->payloadBuilder->buildEventPayload($activity);
$payload = array_merge($payload, $specificPayload);
if ($activity->hasCrmProviderId()) {
$this->logger->info('[Salesforce] Updating crm object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
try {
$this->updateCrmActivity($objectType, $activity, $payload);
} catch (HttpNotFoundException) {
$this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$activity->setCrmProviderId(null);
$activity->save();
}
return;
}
$this->logger->info('[Salesforce] Creating CRM object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$crmProviderId = $this->createRecord($objectType, $payload);
$activity->setCrmProviderId($crmProviderId);
$activity->save();
}
/**
* @throws HttpNotFoundException
*/
private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void
{
$sfActivity = $this->getRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
fields: ['Description', 'WhoId', 'WhatId']
);
if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {
$this->logger->info('[Salesforce] Updating WhoId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {
$this->logger->info('[Salesforce] Updating WhatId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
} else {
$payload['WhatId'] = null;
}
}
$payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(
$payload['Description'],
$sfActivity['Description'] ?? null
);
$this->logger->info('[Salesforce] Updating CRM activity data', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
'crmActivity' => $sfActivity,
'payload' => $payload,
]);
$this->updateRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
data: $payload
);
}
protected function getActivityDecorator(): DecorateActivity
{
if ($this->decorateActivity === null) {
$this->decorateActivity = app(DecorateActivity::class);
}
return $this->decorateActivity;
}
private function resetLeadAssociation(Activity $activity): void
{
$activity->setStageId(null);
$activity->setLeadId(null);
$activity->save();
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"6","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits;\n\nuse Illuminate\\Events\\Dispatcher;\nuse Jiminny\\Events\\Activities\\Crm\\ActivityLeadConverted;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Feature\\FeatureEnum;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Services\\Crm\\Helpers\\CrmHelperRepository;\nuse Jiminny\\Services\\Crm\\Salesforce\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Salesforce\\PayloadBuilder;\nuse Psr\\Log\\LoggerInterface;\n\ntrait LogActivityTrait\n{\n public ?Configuration $config;\n public ?Profile $profile;\n\n protected PayloadBuilder $payloadBuilder;\n protected LoggerInterface $logger;\n protected Dispatcher $eventDispatcher;\n protected CrmHelperRepository $crmHelperRepository;\n protected ?DecorateActivity $decorateActivity = null;\n\n abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;\n abstract public function matchesCrmType(PlaybookCategory $category): bool;\n\n abstract public function syncLead(string $crmId): ?Lead;\n abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;\n abstract public function createRecord(string $objectType, array $data): string;\n abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;\n\n /**\n * Save an activity, update CRM prospect objects\n *\n * Create or update a task or event (depending on most applicable playbook)\n */\n public function saveActivity(Activity $activity): Activity\n {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n throw new InvalidArgumentException('Please configure a Playbook first.');\n }\n\n $this->logger->info('[Salesforce] Log activity', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n ]);\n\n $payload = [\n 'OwnerId' => $this->profile->getCrmProviderId(),\n 'Description' => $this->getActivityDecorator()->generateDescription($activity),\n ];\n\n $payload += $this->buildSubjectPayload($activity, $playbook);\n $payload += $this->buildProspectPayload($activity);\n\n $crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK\n ? Field::OBJECT_TASK\n : Field::OBJECT_EVENT;\n\n $this->logger->info('[Salesforce] Log activity. Payload Prepared', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n 'crm_object_type' => $crmObjectType,\n 'payload' => $payload,\n ]);\n\n $this->saveCrmObject($crmObjectType, $activity, $payload);\n\n return $activity;\n }\n\n private function buildSubjectPayload(Activity $activity, Playbook $playbook): array\n {\n if ($this->matchesCrmType($activity->getCategory())) {\n /**\n * If the activity playbook category name (i.e. activity type) matches a known activity type that exists\n * in the CRM, then we set the activity type in the payload.\n * Some activity types may be locally created. They shouldn't be sent to Salesforce.\n *\n * The resulting payload attribute will look like:\n * `Type` => 'Cold Call'\n */\n return [\n /** ActivityFieldID => ActivityType */\n $playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),\n 'Subject' => $this->getActivityDecorator()->generateTitle($activity),\n ];\n }\n\n /**\n * Building of the title seems very inconsistent\n * Subject here will be something like:\n * \"Local activity type: Activity Title\"\n */\n $subject = $activity->getCategory()->getName();\n if ($activity->getTitle() !== null) {\n $subject .= ': ' . $activity->getTitle();\n }\n\n return ['Subject' => $subject];\n }\n\n private function buildProspectPayload(Activity $activity): array\n {\n $payload = [];\n\n if ($activity->getAccountId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'account_id' => $activity->getAccountId(),\n 'opportunity_id' => $activity->getOpportunityId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $hasLinkFeature = $this->crmHelperRepository->hasFeature(\n $activity,\n FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS\n );\n\n if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())\n || (! $hasLinkFeature && $activity->getOpportunityId())\n ) {\n $payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();\n } else {\n $payload['WhatId'] = $activity->getAccount()->getCrmProviderId();\n }\n }\n\n if ($activity->getContactId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $payload['WhoId'] = $activity->getContact()->getCrmProviderId();\n } elseif ($activity->getLeadId()) {\n $this->logger->info('[Salesforce] Activity has lead id', [\n 'activity_id' => $activity->getId(),\n 'lead_id' => $activity->getLeadId(),\n ]);\n\n /**\n * An activity may have:\n * a) a contact | account | opportunity (or combinations)\n * b) only a lead\n * c) none of the above\n *\n * An activity should not have a lead, and another prospect object at the same time.\n *\n * This logical flow should not happen naturally, but as a fallback: if an activity has both\n * a Lead and an Account, the account's WhatId takes precedence in the CRM payload.\n * The lead association will be detached locally, but the account WhatId is preserved in Salesforce.\n */\n $payload += $this->handleActivityLead($activity);\n }\n\n return $payload;\n }\n\n private function handleActivityLead(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Activity sync lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Sync lead to pull fresh data. Leads change often,\n * they may get 'converted', and we must handle the new state accordingly\n */\n try {\n $activityLead = $this->syncLead(\n $activity->getLead()->getCrmProviderId()\n );\n } catch (HttpNotFoundException) {\n $this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not found, maybe it's remotely deleted\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n if ($activityLead === null) {\n $this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not loaded, for some reason. It may be remotely found, but locally deleted.\n * Or an important Lead property may be missing, and it cannot be fully imported.\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n /**\n * The lead is not converted, directly use it as WhoId and move on.\n */\n if ($activityLead->getConvertedAt() === null) {\n return [\n 'WhoId' => $activity->getLead()->getCrmProviderId(),\n 'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.\n ];\n }\n\n /**\n * Task/Event payload properties for the CRM update\n */\n $whoId = null;\n $whatId = null;\n\n /**\n * Activity payload properties, that need to be updated.\n */\n $convertedOpportunityId = null;\n $convertedAccountId = null;\n $convertedContactId = null;\n $value = null;\n\n /**\n * If there is converted opportunity, it will update the activity stage.\n * If there isn't an opportunity, a converted account/contact cannot have a stage id,\n * so the activity shouldn't have a stage either.\n */\n $stageId = null;\n\n /**\n * The lead is definitely converted.\n * This means the lead may be associated with an opportunity, account, or contact.\n * The converted lead itself must be detached from the activity,\n * while the converted prospect objects must be associated instead,\n * since they now represent the state of the deal.\n */\n $activity->setLeadId(null);\n\n /**\n * CRM property \"WhatId\" can be either an Opportunity or an Account.\n * For us a converted Opportunity has higher priority than an Account.\n * An Opportunity carries more concrete data, including a reference to the Account record itself.\n */\n if ($activityLead->hasOpportunity()) {\n $convertedOpportunity = $activityLead->getOpportunity();\n\n $convertedOpportunityId = $convertedOpportunity->getId();\n $convertedAccountId = $convertedOpportunity->getAccountId();\n $stageId = $convertedOpportunity->getStageId();\n $value = $convertedOpportunity->getValue();\n\n $whatId = $convertedOpportunity->getCrmProviderId();\n }\n\n if ($activityLead->hasAccount()) {\n $convertedAccount = $activityLead->getAccount();\n\n $convertedAccountId ??= $convertedAccount->getId();\n\n $whatId ??= $convertedAccount->getCrmProviderId();\n }\n\n /**\n * WhoId can only be a Contact or a Lead.\n * Since we are detaching the Lead, it can only be a Contact for the current activity.\n * It does not conflict with any other object.\n */\n if ($activityLead->hasContact()) {\n $convertedContact = $activityLead->getContact();\n\n $convertedContactId = $convertedContact->getId();\n\n $whoId = $convertedContact->getCrmProviderId();\n }\n\n $activity->setOpportunityId($convertedOpportunityId);\n $activity->setAccountId($convertedAccountId);\n $activity->setContactId($convertedContactId);\n $activity->setStageId($stageId);\n $activity->setValue($value);\n\n $activity->save();\n\n $this->eventDispatcher->dispatch(\n new ActivityLeadConverted($activity, $activityLead)\n );\n\n $this->logger->info('[Salesforce] Lead is converted', [\n 'activity_id' => $activity->getId(),\n 'whoId' => $whoId,\n 'whatId' => $whatId,\n ]);\n\n return [\n 'WhoId' => $whoId,\n 'WhatId' => $whatId,\n ];\n }\n\n private function saveCrmObject(string $objectType, Activity $activity, array $payload): void\n {\n /**\n * Tasks and events have different payload structures,\n * so we need to consider the type of the object we are sending to the CRM\n */\n $specificPayload = $objectType === Field::OBJECT_TASK\n ? $this->payloadBuilder->buildTaskPayload($activity)\n : $this->payloadBuilder->buildEventPayload($activity);\n\n $payload = array_merge($payload, $specificPayload);\n\n if ($activity->hasCrmProviderId()) {\n $this->logger->info('[Salesforce] Updating crm object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n try {\n $this->updateCrmActivity($objectType, $activity, $payload);\n } catch (HttpNotFoundException) {\n $this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $activity->setCrmProviderId(null);\n $activity->save();\n }\n\n return;\n }\n\n $this->logger->info('[Salesforce] Creating CRM object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $crmProviderId = $this->createRecord($objectType, $payload);\n\n $activity->setCrmProviderId($crmProviderId);\n $activity->save();\n }\n\n /**\n * @throws HttpNotFoundException\n */\n private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void\n {\n $sfActivity = $this->getRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n fields: ['Description', 'WhoId', 'WhatId']\n );\n\n if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {\n $this->logger->info('[Salesforce] Updating WhoId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n\n if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {\n $this->logger->info('[Salesforce] Updating WhatId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n } else {\n $payload['WhatId'] = null;\n }\n }\n\n $payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(\n $payload['Description'],\n $sfActivity['Description'] ?? null\n );\n\n $this->logger->info('[Salesforce] Updating CRM activity data', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n 'crmActivity' => $sfActivity,\n 'payload' => $payload,\n ]);\n\n $this->updateRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n data: $payload\n );\n }\n\n protected function getActivityDecorator(): DecorateActivity\n {\n if ($this->decorateActivity === null) {\n $this->decorateActivity = app(DecorateActivity::class);\n }\n\n return $this->decorateActivity;\n }\n\n private function resetLeadAssociation(Activity $activity): void\n {\n $activity->setStageId(null);\n $activity->setLeadId(null);\n $activity->save();\n }\n}","depth":4,"bounds":{"left":0.43882978,"top":0.5434956,"width":0.31848404,"height":0.4565044},"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits;\n\nuse Illuminate\\Events\\Dispatcher;\nuse Jiminny\\Events\\Activities\\Crm\\ActivityLeadConverted;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Feature\\FeatureEnum;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Services\\Crm\\Helpers\\CrmHelperRepository;\nuse Jiminny\\Services\\Crm\\Salesforce\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Salesforce\\PayloadBuilder;\nuse Psr\\Log\\LoggerInterface;\n\ntrait LogActivityTrait\n{\n public ?Configuration $config;\n public ?Profile $profile;\n\n protected PayloadBuilder $payloadBuilder;\n protected LoggerInterface $logger;\n protected Dispatcher $eventDispatcher;\n protected CrmHelperRepository $crmHelperRepository;\n protected ?DecorateActivity $decorateActivity = null;\n\n abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;\n abstract public function matchesCrmType(PlaybookCategory $category): bool;\n\n abstract public function syncLead(string $crmId): ?Lead;\n abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;\n abstract public function createRecord(string $objectType, array $data): string;\n abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;\n\n /**\n * Save an activity, update CRM prospect objects\n *\n * Create or update a task or event (depending on most applicable playbook)\n */\n public function saveActivity(Activity $activity): Activity\n {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n throw new InvalidArgumentException('Please configure a Playbook first.');\n }\n\n $this->logger->info('[Salesforce] Log activity', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n ]);\n\n $payload = [\n 'OwnerId' => $this->profile->getCrmProviderId(),\n 'Description' => $this->getActivityDecorator()->generateDescription($activity),\n ];\n\n $payload += $this->buildSubjectPayload($activity, $playbook);\n $payload += $this->buildProspectPayload($activity);\n\n $crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK\n ? Field::OBJECT_TASK\n : Field::OBJECT_EVENT;\n\n $this->logger->info('[Salesforce] Log activity. Payload Prepared', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n 'crm_object_type' => $crmObjectType,\n 'payload' => $payload,\n ]);\n\n $this->saveCrmObject($crmObjectType, $activity, $payload);\n\n return $activity;\n }\n\n private function buildSubjectPayload(Activity $activity, Playbook $playbook): array\n {\n if ($this->matchesCrmType($activity->getCategory())) {\n /**\n * If the activity playbook category name (i.e. activity type) matches a known activity type that exists\n * in the CRM, then we set the activity type in the payload.\n * Some activity types may be locally created. They shouldn't be sent to Salesforce.\n *\n * The resulting payload attribute will look like:\n * `Type` => 'Cold Call'\n */\n return [\n /** ActivityFieldID => ActivityType */\n $playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),\n 'Subject' => $this->getActivityDecorator()->generateTitle($activity),\n ];\n }\n\n /**\n * Building of the title seems very inconsistent\n * Subject here will be something like:\n * \"Local activity type: Activity Title\"\n */\n $subject = $activity->getCategory()->getName();\n if ($activity->getTitle() !== null) {\n $subject .= ': ' . $activity->getTitle();\n }\n\n return ['Subject' => $subject];\n }\n\n private function buildProspectPayload(Activity $activity): array\n {\n $payload = [];\n\n if ($activity->getAccountId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'account_id' => $activity->getAccountId(),\n 'opportunity_id' => $activity->getOpportunityId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $hasLinkFeature = $this->crmHelperRepository->hasFeature(\n $activity,\n FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS\n );\n\n if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())\n || (! $hasLinkFeature && $activity->getOpportunityId())\n ) {\n $payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();\n } else {\n $payload['WhatId'] = $activity->getAccount()->getCrmProviderId();\n }\n }\n\n if ($activity->getContactId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $payload['WhoId'] = $activity->getContact()->getCrmProviderId();\n } elseif ($activity->getLeadId()) {\n $this->logger->info('[Salesforce] Activity has lead id', [\n 'activity_id' => $activity->getId(),\n 'lead_id' => $activity->getLeadId(),\n ]);\n\n /**\n * An activity may have:\n * a) a contact | account | opportunity (or combinations)\n * b) only a lead\n * c) none of the above\n *\n * An activity should not have a lead, and another prospect object at the same time.\n *\n * This logical flow should not happen naturally, but as a fallback: if an activity has both\n * a Lead and an Account, the account's WhatId takes precedence in the CRM payload.\n * The lead association will be detached locally, but the account WhatId is preserved in Salesforce.\n */\n $payload += $this->handleActivityLead($activity);\n }\n\n return $payload;\n }\n\n private function handleActivityLead(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Activity sync lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Sync lead to pull fresh data. Leads change often,\n * they may get 'converted', and we must handle the new state accordingly\n */\n try {\n $activityLead = $this->syncLead(\n $activity->getLead()->getCrmProviderId()\n );\n } catch (HttpNotFoundException) {\n $this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not found, maybe it's remotely deleted\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n if ($activityLead === null) {\n $this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not loaded, for some reason. It may be remotely found, but locally deleted.\n * Or an important Lead property may be missing, and it cannot be fully imported.\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n /**\n * The lead is not converted, directly use it as WhoId and move on.\n */\n if ($activityLead->getConvertedAt() === null) {\n return [\n 'WhoId' => $activity->getLead()->getCrmProviderId(),\n 'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.\n ];\n }\n\n /**\n * Task/Event payload properties for the CRM update\n */\n $whoId = null;\n $whatId = null;\n\n /**\n * Activity payload properties, that need to be updated.\n */\n $convertedOpportunityId = null;\n $convertedAccountId = null;\n $convertedContactId = null;\n $value = null;\n\n /**\n * If there is converted opportunity, it will update the activity stage.\n * If there isn't an opportunity, a converted account/contact cannot have a stage id,\n * so the activity shouldn't have a stage either.\n */\n $stageId = null;\n\n /**\n * The lead is definitely converted.\n * This means the lead may be associated with an opportunity, account, or contact.\n * The converted lead itself must be detached from the activity,\n * while the converted prospect objects must be associated instead,\n * since they now represent the state of the deal.\n */\n $activity->setLeadId(null);\n\n /**\n * CRM property \"WhatId\" can be either an Opportunity or an Account.\n * For us a converted Opportunity has higher priority than an Account.\n * An Opportunity carries more concrete data, including a reference to the Account record itself.\n */\n if ($activityLead->hasOpportunity()) {\n $convertedOpportunity = $activityLead->getOpportunity();\n\n $convertedOpportunityId = $convertedOpportunity->getId();\n $convertedAccountId = $convertedOpportunity->getAccountId();\n $stageId = $convertedOpportunity->getStageId();\n $value = $convertedOpportunity->getValue();\n\n $whatId = $convertedOpportunity->getCrmProviderId();\n }\n\n if ($activityLead->hasAccount()) {\n $convertedAccount = $activityLead->getAccount();\n\n $convertedAccountId ??= $convertedAccount->getId();\n\n $whatId ??= $convertedAccount->getCrmProviderId();\n }\n\n /**\n * WhoId can only be a Contact or a Lead.\n * Since we are detaching the Lead, it can only be a Contact for the current activity.\n * It does not conflict with any other object.\n */\n if ($activityLead->hasContact()) {\n $convertedContact = $activityLead->getContact();\n\n $convertedContactId = $convertedContact->getId();\n\n $whoId = $convertedContact->getCrmProviderId();\n }\n\n $activity->setOpportunityId($convertedOpportunityId);\n $activity->setAccountId($convertedAccountId);\n $activity->setContactId($convertedContactId);\n $activity->setStageId($stageId);\n $activity->setValue($value);\n\n $activity->save();\n\n $this->eventDispatcher->dispatch(\n new ActivityLeadConverted($activity, $activityLead)\n );\n\n $this->logger->info('[Salesforce] Lead is converted', [\n 'activity_id' => $activity->getId(),\n 'whoId' => $whoId,\n 'whatId' => $whatId,\n ]);\n\n return [\n 'WhoId' => $whoId,\n 'WhatId' => $whatId,\n ];\n }\n\n private function saveCrmObject(string $objectType, Activity $activity, array $payload): void\n {\n /**\n * Tasks and events have different payload structures,\n * so we need to consider the type of the object we are sending to the CRM\n */\n $specificPayload = $objectType === Field::OBJECT_TASK\n ? $this->payloadBuilder->buildTaskPayload($activity)\n : $this->payloadBuilder->buildEventPayload($activity);\n\n $payload = array_merge($payload, $specificPayload);\n\n if ($activity->hasCrmProviderId()) {\n $this->logger->info('[Salesforce] Updating crm object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n try {\n $this->updateCrmActivity($objectType, $activity, $payload);\n } catch (HttpNotFoundException) {\n $this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $activity->setCrmProviderId(null);\n $activity->save();\n }\n\n return;\n }\n\n $this->logger->info('[Salesforce] Creating CRM object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $crmProviderId = $this->createRecord($objectType, $payload);\n\n $activity->setCrmProviderId($crmProviderId);\n $activity->save();\n }\n\n /**\n * @throws HttpNotFoundException\n */\n private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void\n {\n $sfActivity = $this->getRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n fields: ['Description', 'WhoId', 'WhatId']\n );\n\n if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {\n $this->logger->info('[Salesforce] Updating WhoId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n\n if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {\n $this->logger->info('[Salesforce] Updating WhatId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n } else {\n $payload['WhatId'] = null;\n }\n }\n\n $payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(\n $payload['Description'],\n $sfActivity['Description'] ?? null\n );\n\n $this->logger->info('[Salesforce] Updating CRM activity data', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n 'crmActivity' => $sfActivity,\n 'payload' => $payload,\n ]);\n\n $this->updateRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n data: $payload\n );\n }\n\n protected function getActivityDecorator(): DecorateActivity\n {\n if ($this->decorateActivity === null) {\n $this->decorateActivity = app(DecorateActivity::class);\n }\n\n return $this->decorateActivity;\n }\n\n private function resetLeadAssociation(Activity $activity): void\n {\n $activity->setStageId(null);\n $activity->setLeadId(null);\n $activity->save();\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.28224733,"top":1.0,"width":0.024268618,"height":-0.04788506},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
9077963656576291944
|
5299220392384270933
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
6
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Salesforce\ServiceTraits;
use Illuminate\Events\Dispatcher;
use Jiminny\Events\Activities\Crm\ActivityLeadConverted;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Feature\FeatureEnum;
use Jiminny\Models\Lead;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Services\Crm\Helpers\CrmHelperRepository;
use Jiminny\Services\Crm\Salesforce\DecorateActivity;
use Jiminny\Services\Crm\Salesforce\PayloadBuilder;
use Psr\Log\LoggerInterface;
trait LogActivityTrait
{
public ?Configuration $config;
public ?Profile $profile;
protected PayloadBuilder $payloadBuilder;
protected LoggerInterface $logger;
protected Dispatcher $eventDispatcher;
protected CrmHelperRepository $crmHelperRepository;
protected ?DecorateActivity $decorateActivity = null;
abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;
abstract public function matchesCrmType(PlaybookCategory $category): bool;
abstract public function syncLead(string $crmId): ?Lead;
abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;
abstract public function createRecord(string $objectType, array $data): string;
abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;
/**
* Save an activity, update CRM prospect objects
*
* Create or update a task or event (depending on most applicable playbook)
*/
public function saveActivity(Activity $activity): Activity
{
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
throw new InvalidArgumentException('Please configure a Playbook first.');
}
$this->logger->info('[Salesforce] Log activity', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
]);
$payload = [
'OwnerId' => $this->profile->getCrmProviderId(),
'Description' => $this->getActivityDecorator()->generateDescription($activity),
];
$payload += $this->buildSubjectPayload($activity, $playbook);
$payload += $this->buildProspectPayload($activity);
$crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK
? Field::OBJECT_TASK
: Field::OBJECT_EVENT;
$this->logger->info('[Salesforce] Log activity. Payload Prepared', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
'crm_object_type' => $crmObjectType,
'payload' => $payload,
]);
$this->saveCrmObject($crmObjectType, $activity, $payload);
return $activity;
}
private function buildSubjectPayload(Activity $activity, Playbook $playbook): array
{
if ($this->matchesCrmType($activity->getCategory())) {
/**
* If the activity playbook category name (i.e. activity type) matches a known activity type that exists
* in the CRM, then we set the activity type in the payload.
* Some activity types may be locally created. They shouldn't be sent to Salesforce.
*
* The resulting payload attribute will look like:
* `Type` => 'Cold Call'
*/
return [
/** ActivityFieldID => ActivityType */
$playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),
'Subject' => $this->getActivityDecorator()->generateTitle($activity),
];
}
/**
* Building of the title seems very inconsistent
* Subject here will be something like:
* "Local activity type: Activity Title"
*/
$subject = $activity->getCategory()->getName();
if ($activity->getTitle() !== null) {
$subject .= ': ' . $activity->getTitle();
}
return ['Subject' => $subject];
}
private function buildProspectPayload(Activity $activity): array
{
$payload = [];
if ($activity->getAccountId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'account_id' => $activity->getAccountId(),
'opportunity_id' => $activity->getOpportunityId(),
'contact_id' => $activity->getContactId(),
]);
$hasLinkFeature = $this->crmHelperRepository->hasFeature(
$activity,
FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS
);
if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())
|| (! $hasLinkFeature && $activity->getOpportunityId())
) {
$payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();
} else {
$payload['WhatId'] = $activity->getAccount()->getCrmProviderId();
}
}
if ($activity->getContactId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'contact_id' => $activity->getContactId(),
]);
$payload['WhoId'] = $activity->getContact()->getCrmProviderId();
} elseif ($activity->getLeadId()) {
$this->logger->info('[Salesforce] Activity has lead id', [
'activity_id' => $activity->getId(),
'lead_id' => $activity->getLeadId(),
]);
/**
* An activity may have:
* a) a contact | account | opportunity (or combinations)
* b) only a lead
* c) none of the above
*
* An activity should not have a lead, and another prospect object at the same time.
*
* This logical flow should not happen naturally, but as a fallback: if an activity has both
* a Lead and an Account, the account's WhatId takes precedence in the CRM payload.
* The lead association will be detached locally, but the account WhatId is preserved in Salesforce.
*/
$payload += $this->handleActivityLead($activity);
}
return $payload;
}
private function handleActivityLead(Activity $activity): array
{
$this->logger->info('[Salesforce] Activity sync lead', [
'activity_id' => $activity->getId(),
]);
/**
* Sync lead to pull fresh data. Leads change often,
* they may get 'converted', and we must handle the new state accordingly
*/
try {
$activityLead = $this->syncLead(
$activity->getLead()->getCrmProviderId()
);
} catch (HttpNotFoundException) {
$this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not found, maybe it's remotely deleted
*/
$this->resetLeadAssociation($activity);
return [];
}
if ($activityLead === null) {
$this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not loaded, for some reason. It may be remotely found, but locally deleted.
* Or an important Lead property may be missing, and it cannot be fully imported.
*/
$this->resetLeadAssociation($activity);
return [];
}
/**
* The lead is not converted, directly use it as WhoId and move on.
*/
if ($activityLead->getConvertedAt() === null) {
return [
'WhoId' => $activity->getLead()->getCrmProviderId(),
'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.
];
}
/**
* Task/Event payload properties for the CRM update
*/
$whoId = null;
$whatId = null;
/**
* Activity payload properties, that need to be updated.
*/
$convertedOpportunityId = null;
$convertedAccountId = null;
$convertedContactId = null;
$value = null;
/**
* If there is converted opportunity, it will update the activity stage.
* If there isn't an opportunity, a converted account/contact cannot have a stage id,
* so the activity shouldn't have a stage either.
*/
$stageId = null;
/**
* The lead is definitely converted.
* This means the lead may be associated with an opportunity, account, or contact.
* The converted lead itself must be detached from the activity,
* while the converted prospect objects must be associated instead,
* since they now represent the state of the deal.
*/
$activity->setLeadId(null);
/**
* CRM property "WhatId" can be either an Opportunity or an Account.
* For us a converted Opportunity has higher priority than an Account.
* An Opportunity carries more concrete data, including a reference to the Account record itself.
*/
if ($activityLead->hasOpportunity()) {
$convertedOpportunity = $activityLead->getOpportunity();
$convertedOpportunityId = $convertedOpportunity->getId();
$convertedAccountId = $convertedOpportunity->getAccountId();
$stageId = $convertedOpportunity->getStageId();
$value = $convertedOpportunity->getValue();
$whatId = $convertedOpportunity->getCrmProviderId();
}
if ($activityLead->hasAccount()) {
$convertedAccount = $activityLead->getAccount();
$convertedAccountId ??= $convertedAccount->getId();
$whatId ??= $convertedAccount->getCrmProviderId();
}
/**
* WhoId can only be a Contact or a Lead.
* Since we are detaching the Lead, it can only be a Contact for the current activity.
* It does not conflict with any other object.
*/
if ($activityLead->hasContact()) {
$convertedContact = $activityLead->getContact();
$convertedContactId = $convertedContact->getId();
$whoId = $convertedContact->getCrmProviderId();
}
$activity->setOpportunityId($convertedOpportunityId);
$activity->setAccountId($convertedAccountId);
$activity->setContactId($convertedContactId);
$activity->setStageId($stageId);
$activity->setValue($value);
$activity->save();
$this->eventDispatcher->dispatch(
new ActivityLeadConverted($activity, $activityLead)
);
$this->logger->info('[Salesforce] Lead is converted', [
'activity_id' => $activity->getId(),
'whoId' => $whoId,
'whatId' => $whatId,
]);
return [
'WhoId' => $whoId,
'WhatId' => $whatId,
];
}
private function saveCrmObject(string $objectType, Activity $activity, array $payload): void
{
/**
* Tasks and events have different payload structures,
* so we need to consider the type of the object we are sending to the CRM
*/
$specificPayload = $objectType === Field::OBJECT_TASK
? $this->payloadBuilder->buildTaskPayload($activity)
: $this->payloadBuilder->buildEventPayload($activity);
$payload = array_merge($payload, $specificPayload);
if ($activity->hasCrmProviderId()) {
$this->logger->info('[Salesforce] Updating crm object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
try {
$this->updateCrmActivity($objectType, $activity, $payload);
} catch (HttpNotFoundException) {
$this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$activity->setCrmProviderId(null);
$activity->save();
}
return;
}
$this->logger->info('[Salesforce] Creating CRM object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$crmProviderId = $this->createRecord($objectType, $payload);
$activity->setCrmProviderId($crmProviderId);
$activity->save();
}
/**
* @throws HttpNotFoundException
*/
private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void
{
$sfActivity = $this->getRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
fields: ['Description', 'WhoId', 'WhatId']
);
if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {
$this->logger->info('[Salesforce] Updating WhoId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {
$this->logger->info('[Salesforce] Updating WhatId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
} else {
$payload['WhatId'] = null;
}
}
$payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(
$payload['Description'],
$sfActivity['Description'] ?? null
);
$this->logger->info('[Salesforce] Updating CRM activity data', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
'crmActivity' => $sfActivity,
'payload' => $payload,
]);
$this->updateRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
data: $payload
);
}
protected function getActivityDecorator(): DecorateActivity
{
if ($this->decorateActivity === null) {
$this->decorateActivity = app(DecorateActivity::class);
}
return $this->decorateActivity;
}
private function resetLeadAssociation(Activity $activity): void
{
$activity->setStageId(null);
$activity->setLeadId(null);
$activity->save();
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
45269
|
NULL
|
NULL
|
NULL
|
|
45272
|
1623
|
16
|
2026-05-14T14:28:11.160963+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768891160_m1.jpg...
|
PhpStorm
|
faVsco.js – LogActivityTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
6
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Salesforce\ServiceTraits;
use Illuminate\Events\Dispatcher;
use Jiminny\Events\Activities\Crm\ActivityLeadConverted;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Feature\FeatureEnum;
use Jiminny\Models\Lead;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Services\Crm\Helpers\CrmHelperRepository;
use Jiminny\Services\Crm\Salesforce\DecorateActivity;
use Jiminny\Services\Crm\Salesforce\PayloadBuilder;
use Psr\Log\LoggerInterface;
trait LogActivityTrait
{
public ?Configuration $config;
public ?Profile $profile;
protected PayloadBuilder $payloadBuilder;
protected LoggerInterface $logger;
protected Dispatcher $eventDispatcher;
protected CrmHelperRepository $crmHelperRepository;
protected ?DecorateActivity $decorateActivity = null;
abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;
abstract public function matchesCrmType(PlaybookCategory $category): bool;
abstract public function syncLead(string $crmId): ?Lead;
abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;
abstract public function createRecord(string $objectType, array $data): string;
abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;
/**
* Save an activity, update CRM prospect objects
*
* Create or update a task or event (depending on most applicable playbook)
*/
public function saveActivity(Activity $activity): Activity
{
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
throw new InvalidArgumentException('Please configure a Playbook first.');
}
$this->logger->info('[Salesforce] Log activity', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
]);
$payload = [
'OwnerId' => $this->profile->getCrmProviderId(),
'Description' => $this->getActivityDecorator()->generateDescription($activity),
];
$payload += $this->buildSubjectPayload($activity, $playbook);
$payload += $this->buildProspectPayload($activity);
$crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK
? Field::OBJECT_TASK
: Field::OBJECT_EVENT;
$this->logger->info('[Salesforce] Log activity. Payload Prepared', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
'crm_object_type' => $crmObjectType,
'payload' => $payload,
]);
$this->saveCrmObject($crmObjectType, $activity, $payload);
return $activity;
}
private function buildSubjectPayload(Activity $activity, Playbook $playbook): array
{
if ($this->matchesCrmType($activity->getCategory())) {
/**
* If the activity playbook category name (i.e. activity type) matches a known activity type that exists
* in the CRM, then we set the activity type in the payload.
* Some activity types may be locally created. They shouldn't be sent to Salesforce.
*
* The resulting payload attribute will look like:
* `Type` => 'Cold Call'
*/
return [
/** ActivityFieldID => ActivityType */
$playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),
'Subject' => $this->getActivityDecorator()->generateTitle($activity),
];
}
/**
* Building of the title seems very inconsistent
* Subject here will be something like:
* "Local activity type: Activity Title"
*/
$subject = $activity->getCategory()->getName();
if ($activity->getTitle() !== null) {
$subject .= ': ' . $activity->getTitle();
}
return ['Subject' => $subject];
}
private function buildProspectPayload(Activity $activity): array
{
$payload = [];
if ($activity->getAccountId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'account_id' => $activity->getAccountId(),
'opportunity_id' => $activity->getOpportunityId(),
'contact_id' => $activity->getContactId(),
]);
$hasLinkFeature = $this->crmHelperRepository->hasFeature(
$activity,
FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS
);
if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())
|| (! $hasLinkFeature && $activity->getOpportunityId())
) {
$payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();
} else {
$payload['WhatId'] = $activity->getAccount()->getCrmProviderId();
}
}
if ($activity->getContactId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'contact_id' => $activity->getContactId(),
]);
$payload['WhoId'] = $activity->getContact()->getCrmProviderId();
} elseif ($activity->getLeadId()) {
$this->logger->info('[Salesforce] Activity has lead id', [
'activity_id' => $activity->getId(),
'lead_id' => $activity->getLeadId(),
]);
/**
* An activity may have:
* a) a contact | account | opportunity (or combinations)
* b) only a lead
* c) none of the above
*
* An activity should not have a lead, and another prospect object at the same time.
*
* This logical flow should not happen naturally, but as a fallback: if an activity has both
* a Lead and an Account, the account's WhatId takes precedence in the CRM payload.
* The lead association will be detached locally, but the account WhatId is preserved in Salesforce.
*/
$payload += $this->handleActivityLead($activity);
}
return $payload;
}
private function handleActivityLead(Activity $activity): array
{
$this->logger->info('[Salesforce] Activity sync lead', [
'activity_id' => $activity->getId(),
]);
/**
* Sync lead to pull fresh data. Leads change often,
* they may get 'converted', and we must handle the new state accordingly
*/
try {
$activityLead = $this->syncLead(
$activity->getLead()->getCrmProviderId()
);
} catch (HttpNotFoundException) {
$this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not found, maybe it's remotely deleted
*/
$this->resetLeadAssociation($activity);
return [];
}
if ($activityLead === null) {
$this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not loaded, for some reason. It may be remotely found, but locally deleted.
* Or an important Lead property may be missing, and it cannot be fully imported.
*/
$this->resetLeadAssociation($activity);
return [];
}
/**
* The lead is not converted, directly use it as WhoId and move on.
*/
if ($activityLead->getConvertedAt() === null) {
return [
'WhoId' => $activity->getLead()->getCrmProviderId(),
'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.
];
}
/**
* Task/Event payload properties for the CRM update
*/
$whoId = null;
$whatId = null;
/**
* Activity payload properties, that need to be updated.
*/
$convertedOpportunityId = null;
$convertedAccountId = null;
$convertedContactId = null;
$value = null;
/**
* If there is converted opportunity, it will update the activity stage.
* If there isn't an opportunity, a converted account/contact cannot have a stage id,
* so the activity shouldn't have a stage either.
*/
$stageId = null;
/**
* The lead is definitely converted.
* This means the lead may be associated with an opportunity, account, or contact.
* The converted lead itself must be detached from the activity,
* while the converted prospect objects must be associated instead,
* since they now represent the state of the deal.
*/
$activity->setLeadId(null);
/**
* CRM property "WhatId" can be either an Opportunity or an Account.
* For us a converted Opportunity has higher priority than an Account.
* An Opportunity carries more concrete data, including a reference to the Account record itself.
*/
if ($activityLead->hasOpportunity()) {
$convertedOpportunity = $activityLead->getOpportunity();
$convertedOpportunityId = $convertedOpportunity->getId();
$convertedAccountId = $convertedOpportunity->getAccountId();
$stageId = $convertedOpportunity->getStageId();
$value = $convertedOpportunity->getValue();
$whatId = $convertedOpportunity->getCrmProviderId();
}
if ($activityLead->hasAccount()) {
$convertedAccount = $activityLead->getAccount();
$convertedAccountId ??= $convertedAccount->getId();
$whatId ??= $convertedAccount->getCrmProviderId();
}
/**
* WhoId can only be a Contact or a Lead.
* Since we are detaching the Lead, it can only be a Contact for the current activity.
* It does not conflict with any other object.
*/
if ($activityLead->hasContact()) {
$convertedContact = $activityLead->getContact();
$convertedContactId = $convertedContact->getId();
$whoId = $convertedContact->getCrmProviderId();
}
$activity->setOpportunityId($convertedOpportunityId);
$activity->setAccountId($convertedAccountId);
$activity->setContactId($convertedContactId);
$activity->setStageId($stageId);
$activity->setValue($value);
$activity->save();
$this->eventDispatcher->dispatch(
new ActivityLeadConverted($activity, $activityLead)
);
$this->logger->info('[Salesforce] Lead is converted', [
'activity_id' => $activity->getId(),
'whoId' => $whoId,
'whatId' => $whatId,
]);
return [
'WhoId' => $whoId,
'WhatId' => $whatId,
];
}
private function saveCrmObject(string $objectType, Activity $activity, array $payload): void
{
/**
* Tasks and events have different payload structures,
* so we need to consider the type of the object we are sending to the CRM
*/
$specificPayload = $objectType === Field::OBJECT_TASK
? $this->payloadBuilder->buildTaskPayload($activity)
: $this->payloadBuilder->buildEventPayload($activity);
$payload = array_merge($payload, $specificPayload);
if ($activity->hasCrmProviderId()) {
$this->logger->info('[Salesforce] Updating crm object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
try {
$this->updateCrmActivity($objectType, $activity, $payload);
} catch (HttpNotFoundException) {
$this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$activity->setCrmProviderId(null);
$activity->save();
}
return;
}
$this->logger->info('[Salesforce] Creating CRM object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$crmProviderId = $this->createRecord($objectType, $payload);
$activity->setCrmProviderId($crmProviderId);
$activity->save();
}
/**
* @throws HttpNotFoundException
*/
private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void
{
$sfActivity = $this->getRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
fields: ['Description', 'WhoId', 'WhatId']
);
if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {
$this->logger->info('[Salesforce] Updating WhoId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {
$this->logger->info('[Salesforce] Updating WhatId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
} else {
$payload['WhatId'] = null;
}
}
$payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(
$payload['Description'],
$sfActivity['Description'] ?? null
);
$this->logger->info('[Salesforce] Updating CRM activity data', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
'crmActivity' => $sfActivity,
'payload' => $payload,
]);
$this->updateRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
data: $payload
);
}
protected function getActivityDecorator(): DecorateActivity
{
if ($this->decorateActivity === null) {
$this->decorateActivity = app(DecorateActivity::class);
}
return $this->decorateActivity;
}
private function resetLeadAssociation(Activity $activity): void
{
$activity->setStageId(null);
$activity->setLeadId(null);
$activity->save();
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"6","depth":4,"bounds":{"left":0.78194445,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.80277777,"top":0.3122222,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits;\n\nuse Illuminate\\Events\\Dispatcher;\nuse Jiminny\\Events\\Activities\\Crm\\ActivityLeadConverted;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Feature\\FeatureEnum;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Services\\Crm\\Helpers\\CrmHelperRepository;\nuse Jiminny\\Services\\Crm\\Salesforce\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Salesforce\\PayloadBuilder;\nuse Psr\\Log\\LoggerInterface;\n\ntrait LogActivityTrait\n{\n public ?Configuration $config;\n public ?Profile $profile;\n\n protected PayloadBuilder $payloadBuilder;\n protected LoggerInterface $logger;\n protected Dispatcher $eventDispatcher;\n protected CrmHelperRepository $crmHelperRepository;\n protected ?DecorateActivity $decorateActivity = null;\n\n abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;\n abstract public function matchesCrmType(PlaybookCategory $category): bool;\n\n abstract public function syncLead(string $crmId): ?Lead;\n abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;\n abstract public function createRecord(string $objectType, array $data): string;\n abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;\n\n /**\n * Save an activity, update CRM prospect objects\n *\n * Create or update a task or event (depending on most applicable playbook)\n */\n public function saveActivity(Activity $activity): Activity\n {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n throw new InvalidArgumentException('Please configure a Playbook first.');\n }\n\n $this->logger->info('[Salesforce] Log activity', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n ]);\n\n $payload = [\n 'OwnerId' => $this->profile->getCrmProviderId(),\n 'Description' => $this->getActivityDecorator()->generateDescription($activity),\n ];\n\n $payload += $this->buildSubjectPayload($activity, $playbook);\n $payload += $this->buildProspectPayload($activity);\n\n $crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK\n ? Field::OBJECT_TASK\n : Field::OBJECT_EVENT;\n\n $this->logger->info('[Salesforce] Log activity. Payload Prepared', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n 'crm_object_type' => $crmObjectType,\n 'payload' => $payload,\n ]);\n\n $this->saveCrmObject($crmObjectType, $activity, $payload);\n\n return $activity;\n }\n\n private function buildSubjectPayload(Activity $activity, Playbook $playbook): array\n {\n if ($this->matchesCrmType($activity->getCategory())) {\n /**\n * If the activity playbook category name (i.e. activity type) matches a known activity type that exists\n * in the CRM, then we set the activity type in the payload.\n * Some activity types may be locally created. They shouldn't be sent to Salesforce.\n *\n * The resulting payload attribute will look like:\n * `Type` => 'Cold Call'\n */\n return [\n /** ActivityFieldID => ActivityType */\n $playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),\n 'Subject' => $this->getActivityDecorator()->generateTitle($activity),\n ];\n }\n\n /**\n * Building of the title seems very inconsistent\n * Subject here will be something like:\n * \"Local activity type: Activity Title\"\n */\n $subject = $activity->getCategory()->getName();\n if ($activity->getTitle() !== null) {\n $subject .= ': ' . $activity->getTitle();\n }\n\n return ['Subject' => $subject];\n }\n\n private function buildProspectPayload(Activity $activity): array\n {\n $payload = [];\n\n if ($activity->getAccountId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'account_id' => $activity->getAccountId(),\n 'opportunity_id' => $activity->getOpportunityId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $hasLinkFeature = $this->crmHelperRepository->hasFeature(\n $activity,\n FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS\n );\n\n if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())\n || (! $hasLinkFeature && $activity->getOpportunityId())\n ) {\n $payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();\n } else {\n $payload['WhatId'] = $activity->getAccount()->getCrmProviderId();\n }\n }\n\n if ($activity->getContactId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $payload['WhoId'] = $activity->getContact()->getCrmProviderId();\n } elseif ($activity->getLeadId()) {\n $this->logger->info('[Salesforce] Activity has lead id', [\n 'activity_id' => $activity->getId(),\n 'lead_id' => $activity->getLeadId(),\n ]);\n\n /**\n * An activity may have:\n * a) a contact | account | opportunity (or combinations)\n * b) only a lead\n * c) none of the above\n *\n * An activity should not have a lead, and another prospect object at the same time.\n *\n * This logical flow should not happen naturally, but as a fallback: if an activity has both\n * a Lead and an Account, the account's WhatId takes precedence in the CRM payload.\n * The lead association will be detached locally, but the account WhatId is preserved in Salesforce.\n */\n $payload += $this->handleActivityLead($activity);\n }\n\n return $payload;\n }\n\n private function handleActivityLead(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Activity sync lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Sync lead to pull fresh data. Leads change often,\n * they may get 'converted', and we must handle the new state accordingly\n */\n try {\n $activityLead = $this->syncLead(\n $activity->getLead()->getCrmProviderId()\n );\n } catch (HttpNotFoundException) {\n $this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not found, maybe it's remotely deleted\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n if ($activityLead === null) {\n $this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not loaded, for some reason. It may be remotely found, but locally deleted.\n * Or an important Lead property may be missing, and it cannot be fully imported.\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n /**\n * The lead is not converted, directly use it as WhoId and move on.\n */\n if ($activityLead->getConvertedAt() === null) {\n return [\n 'WhoId' => $activity->getLead()->getCrmProviderId(),\n 'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.\n ];\n }\n\n /**\n * Task/Event payload properties for the CRM update\n */\n $whoId = null;\n $whatId = null;\n\n /**\n * Activity payload properties, that need to be updated.\n */\n $convertedOpportunityId = null;\n $convertedAccountId = null;\n $convertedContactId = null;\n $value = null;\n\n /**\n * If there is converted opportunity, it will update the activity stage.\n * If there isn't an opportunity, a converted account/contact cannot have a stage id,\n * so the activity shouldn't have a stage either.\n */\n $stageId = null;\n\n /**\n * The lead is definitely converted.\n * This means the lead may be associated with an opportunity, account, or contact.\n * The converted lead itself must be detached from the activity,\n * while the converted prospect objects must be associated instead,\n * since they now represent the state of the deal.\n */\n $activity->setLeadId(null);\n\n /**\n * CRM property \"WhatId\" can be either an Opportunity or an Account.\n * For us a converted Opportunity has higher priority than an Account.\n * An Opportunity carries more concrete data, including a reference to the Account record itself.\n */\n if ($activityLead->hasOpportunity()) {\n $convertedOpportunity = $activityLead->getOpportunity();\n\n $convertedOpportunityId = $convertedOpportunity->getId();\n $convertedAccountId = $convertedOpportunity->getAccountId();\n $stageId = $convertedOpportunity->getStageId();\n $value = $convertedOpportunity->getValue();\n\n $whatId = $convertedOpportunity->getCrmProviderId();\n }\n\n if ($activityLead->hasAccount()) {\n $convertedAccount = $activityLead->getAccount();\n\n $convertedAccountId ??= $convertedAccount->getId();\n\n $whatId ??= $convertedAccount->getCrmProviderId();\n }\n\n /**\n * WhoId can only be a Contact or a Lead.\n * Since we are detaching the Lead, it can only be a Contact for the current activity.\n * It does not conflict with any other object.\n */\n if ($activityLead->hasContact()) {\n $convertedContact = $activityLead->getContact();\n\n $convertedContactId = $convertedContact->getId();\n\n $whoId = $convertedContact->getCrmProviderId();\n }\n\n $activity->setOpportunityId($convertedOpportunityId);\n $activity->setAccountId($convertedAccountId);\n $activity->setContactId($convertedContactId);\n $activity->setStageId($stageId);\n $activity->setValue($value);\n\n $activity->save();\n\n $this->eventDispatcher->dispatch(\n new ActivityLeadConverted($activity, $activityLead)\n );\n\n $this->logger->info('[Salesforce] Lead is converted', [\n 'activity_id' => $activity->getId(),\n 'whoId' => $whoId,\n 'whatId' => $whatId,\n ]);\n\n return [\n 'WhoId' => $whoId,\n 'WhatId' => $whatId,\n ];\n }\n\n private function saveCrmObject(string $objectType, Activity $activity, array $payload): void\n {\n /**\n * Tasks and events have different payload structures,\n * so we need to consider the type of the object we are sending to the CRM\n */\n $specificPayload = $objectType === Field::OBJECT_TASK\n ? $this->payloadBuilder->buildTaskPayload($activity)\n : $this->payloadBuilder->buildEventPayload($activity);\n\n $payload = array_merge($payload, $specificPayload);\n\n if ($activity->hasCrmProviderId()) {\n $this->logger->info('[Salesforce] Updating crm object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n try {\n $this->updateCrmActivity($objectType, $activity, $payload);\n } catch (HttpNotFoundException) {\n $this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $activity->setCrmProviderId(null);\n $activity->save();\n }\n\n return;\n }\n\n $this->logger->info('[Salesforce] Creating CRM object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $crmProviderId = $this->createRecord($objectType, $payload);\n\n $activity->setCrmProviderId($crmProviderId);\n $activity->save();\n }\n\n /**\n * @throws HttpNotFoundException\n */\n private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void\n {\n $sfActivity = $this->getRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n fields: ['Description', 'WhoId', 'WhatId']\n );\n\n if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {\n $this->logger->info('[Salesforce] Updating WhoId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n\n if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {\n $this->logger->info('[Salesforce] Updating WhatId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n } else {\n $payload['WhatId'] = null;\n }\n }\n\n $payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(\n $payload['Description'],\n $sfActivity['Description'] ?? null\n );\n\n $this->logger->info('[Salesforce] Updating CRM activity data', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n 'crmActivity' => $sfActivity,\n 'payload' => $payload,\n ]);\n\n $this->updateRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n data: $payload\n );\n }\n\n protected function getActivityDecorator(): DecorateActivity\n {\n if ($this->decorateActivity === null) {\n $this->decorateActivity = app(DecorateActivity::class);\n }\n\n return $this->decorateActivity;\n }\n\n private function resetLeadAssociation(Activity $activity): void\n {\n $activity->setStageId(null);\n $activity->setLeadId(null);\n $activity->save();\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits;\n\nuse Illuminate\\Events\\Dispatcher;\nuse Jiminny\\Events\\Activities\\Crm\\ActivityLeadConverted;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Feature\\FeatureEnum;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Services\\Crm\\Helpers\\CrmHelperRepository;\nuse Jiminny\\Services\\Crm\\Salesforce\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Salesforce\\PayloadBuilder;\nuse Psr\\Log\\LoggerInterface;\n\ntrait LogActivityTrait\n{\n public ?Configuration $config;\n public ?Profile $profile;\n\n protected PayloadBuilder $payloadBuilder;\n protected LoggerInterface $logger;\n protected Dispatcher $eventDispatcher;\n protected CrmHelperRepository $crmHelperRepository;\n protected ?DecorateActivity $decorateActivity = null;\n\n abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;\n abstract public function matchesCrmType(PlaybookCategory $category): bool;\n\n abstract public function syncLead(string $crmId): ?Lead;\n abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;\n abstract public function createRecord(string $objectType, array $data): string;\n abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;\n\n /**\n * Save an activity, update CRM prospect objects\n *\n * Create or update a task or event (depending on most applicable playbook)\n */\n public function saveActivity(Activity $activity): Activity\n {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n throw new InvalidArgumentException('Please configure a Playbook first.');\n }\n\n $this->logger->info('[Salesforce] Log activity', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n ]);\n\n $payload = [\n 'OwnerId' => $this->profile->getCrmProviderId(),\n 'Description' => $this->getActivityDecorator()->generateDescription($activity),\n ];\n\n $payload += $this->buildSubjectPayload($activity, $playbook);\n $payload += $this->buildProspectPayload($activity);\n\n $crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK\n ? Field::OBJECT_TASK\n : Field::OBJECT_EVENT;\n\n $this->logger->info('[Salesforce] Log activity. Payload Prepared', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n 'crm_object_type' => $crmObjectType,\n 'payload' => $payload,\n ]);\n\n $this->saveCrmObject($crmObjectType, $activity, $payload);\n\n return $activity;\n }\n\n private function buildSubjectPayload(Activity $activity, Playbook $playbook): array\n {\n if ($this->matchesCrmType($activity->getCategory())) {\n /**\n * If the activity playbook category name (i.e. activity type) matches a known activity type that exists\n * in the CRM, then we set the activity type in the payload.\n * Some activity types may be locally created. They shouldn't be sent to Salesforce.\n *\n * The resulting payload attribute will look like:\n * `Type` => 'Cold Call'\n */\n return [\n /** ActivityFieldID => ActivityType */\n $playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),\n 'Subject' => $this->getActivityDecorator()->generateTitle($activity),\n ];\n }\n\n /**\n * Building of the title seems very inconsistent\n * Subject here will be something like:\n * \"Local activity type: Activity Title\"\n */\n $subject = $activity->getCategory()->getName();\n if ($activity->getTitle() !== null) {\n $subject .= ': ' . $activity->getTitle();\n }\n\n return ['Subject' => $subject];\n }\n\n private function buildProspectPayload(Activity $activity): array\n {\n $payload = [];\n\n if ($activity->getAccountId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'account_id' => $activity->getAccountId(),\n 'opportunity_id' => $activity->getOpportunityId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $hasLinkFeature = $this->crmHelperRepository->hasFeature(\n $activity,\n FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS\n );\n\n if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())\n || (! $hasLinkFeature && $activity->getOpportunityId())\n ) {\n $payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();\n } else {\n $payload['WhatId'] = $activity->getAccount()->getCrmProviderId();\n }\n }\n\n if ($activity->getContactId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $payload['WhoId'] = $activity->getContact()->getCrmProviderId();\n } elseif ($activity->getLeadId()) {\n $this->logger->info('[Salesforce] Activity has lead id', [\n 'activity_id' => $activity->getId(),\n 'lead_id' => $activity->getLeadId(),\n ]);\n\n /**\n * An activity may have:\n * a) a contact | account | opportunity (or combinations)\n * b) only a lead\n * c) none of the above\n *\n * An activity should not have a lead, and another prospect object at the same time.\n *\n * This logical flow should not happen naturally, but as a fallback: if an activity has both\n * a Lead and an Account, the account's WhatId takes precedence in the CRM payload.\n * The lead association will be detached locally, but the account WhatId is preserved in Salesforce.\n */\n $payload += $this->handleActivityLead($activity);\n }\n\n return $payload;\n }\n\n private function handleActivityLead(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Activity sync lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Sync lead to pull fresh data. Leads change often,\n * they may get 'converted', and we must handle the new state accordingly\n */\n try {\n $activityLead = $this->syncLead(\n $activity->getLead()->getCrmProviderId()\n );\n } catch (HttpNotFoundException) {\n $this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not found, maybe it's remotely deleted\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n if ($activityLead === null) {\n $this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not loaded, for some reason. It may be remotely found, but locally deleted.\n * Or an important Lead property may be missing, and it cannot be fully imported.\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n /**\n * The lead is not converted, directly use it as WhoId and move on.\n */\n if ($activityLead->getConvertedAt() === null) {\n return [\n 'WhoId' => $activity->getLead()->getCrmProviderId(),\n 'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.\n ];\n }\n\n /**\n * Task/Event payload properties for the CRM update\n */\n $whoId = null;\n $whatId = null;\n\n /**\n * Activity payload properties, that need to be updated.\n */\n $convertedOpportunityId = null;\n $convertedAccountId = null;\n $convertedContactId = null;\n $value = null;\n\n /**\n * If there is converted opportunity, it will update the activity stage.\n * If there isn't an opportunity, a converted account/contact cannot have a stage id,\n * so the activity shouldn't have a stage either.\n */\n $stageId = null;\n\n /**\n * The lead is definitely converted.\n * This means the lead may be associated with an opportunity, account, or contact.\n * The converted lead itself must be detached from the activity,\n * while the converted prospect objects must be associated instead,\n * since they now represent the state of the deal.\n */\n $activity->setLeadId(null);\n\n /**\n * CRM property \"WhatId\" can be either an Opportunity or an Account.\n * For us a converted Opportunity has higher priority than an Account.\n * An Opportunity carries more concrete data, including a reference to the Account record itself.\n */\n if ($activityLead->hasOpportunity()) {\n $convertedOpportunity = $activityLead->getOpportunity();\n\n $convertedOpportunityId = $convertedOpportunity->getId();\n $convertedAccountId = $convertedOpportunity->getAccountId();\n $stageId = $convertedOpportunity->getStageId();\n $value = $convertedOpportunity->getValue();\n\n $whatId = $convertedOpportunity->getCrmProviderId();\n }\n\n if ($activityLead->hasAccount()) {\n $convertedAccount = $activityLead->getAccount();\n\n $convertedAccountId ??= $convertedAccount->getId();\n\n $whatId ??= $convertedAccount->getCrmProviderId();\n }\n\n /**\n * WhoId can only be a Contact or a Lead.\n * Since we are detaching the Lead, it can only be a Contact for the current activity.\n * It does not conflict with any other object.\n */\n if ($activityLead->hasContact()) {\n $convertedContact = $activityLead->getContact();\n\n $convertedContactId = $convertedContact->getId();\n\n $whoId = $convertedContact->getCrmProviderId();\n }\n\n $activity->setOpportunityId($convertedOpportunityId);\n $activity->setAccountId($convertedAccountId);\n $activity->setContactId($convertedContactId);\n $activity->setStageId($stageId);\n $activity->setValue($value);\n\n $activity->save();\n\n $this->eventDispatcher->dispatch(\n new ActivityLeadConverted($activity, $activityLead)\n );\n\n $this->logger->info('[Salesforce] Lead is converted', [\n 'activity_id' => $activity->getId(),\n 'whoId' => $whoId,\n 'whatId' => $whatId,\n ]);\n\n return [\n 'WhoId' => $whoId,\n 'WhatId' => $whatId,\n ];\n }\n\n private function saveCrmObject(string $objectType, Activity $activity, array $payload): void\n {\n /**\n * Tasks and events have different payload structures,\n * so we need to consider the type of the object we are sending to the CRM\n */\n $specificPayload = $objectType === Field::OBJECT_TASK\n ? $this->payloadBuilder->buildTaskPayload($activity)\n : $this->payloadBuilder->buildEventPayload($activity);\n\n $payload = array_merge($payload, $specificPayload);\n\n if ($activity->hasCrmProviderId()) {\n $this->logger->info('[Salesforce] Updating crm object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n try {\n $this->updateCrmActivity($objectType, $activity, $payload);\n } catch (HttpNotFoundException) {\n $this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $activity->setCrmProviderId(null);\n $activity->save();\n }\n\n return;\n }\n\n $this->logger->info('[Salesforce] Creating CRM object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $crmProviderId = $this->createRecord($objectType, $payload);\n\n $activity->setCrmProviderId($crmProviderId);\n $activity->save();\n }\n\n /**\n * @throws HttpNotFoundException\n */\n private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void\n {\n $sfActivity = $this->getRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n fields: ['Description', 'WhoId', 'WhatId']\n );\n\n if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {\n $this->logger->info('[Salesforce] Updating WhoId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n\n if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {\n $this->logger->info('[Salesforce] Updating WhatId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n } else {\n $payload['WhatId'] = null;\n }\n }\n\n $payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(\n $payload['Description'],\n $sfActivity['Description'] ?? null\n );\n\n $this->logger->info('[Salesforce] Updating CRM activity data', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n 'crmActivity' => $sfActivity,\n 'payload' => $payload,\n ]);\n\n $this->updateRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n data: $payload\n );\n }\n\n protected function getActivityDecorator(): DecorateActivity\n {\n if ($this->decorateActivity === null) {\n $this->decorateActivity = app(DecorateActivity::class);\n }\n\n return $this->decorateActivity;\n }\n\n private function resetLeadAssociation(Activity $activity): void\n {\n $activity->setStageId(null);\n $activity->setLeadId(null);\n $activity->save();\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
9077963656576291944
|
5299220392384270933
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
6
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Salesforce\ServiceTraits;
use Illuminate\Events\Dispatcher;
use Jiminny\Events\Activities\Crm\ActivityLeadConverted;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Feature\FeatureEnum;
use Jiminny\Models\Lead;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Services\Crm\Helpers\CrmHelperRepository;
use Jiminny\Services\Crm\Salesforce\DecorateActivity;
use Jiminny\Services\Crm\Salesforce\PayloadBuilder;
use Psr\Log\LoggerInterface;
trait LogActivityTrait
{
public ?Configuration $config;
public ?Profile $profile;
protected PayloadBuilder $payloadBuilder;
protected LoggerInterface $logger;
protected Dispatcher $eventDispatcher;
protected CrmHelperRepository $crmHelperRepository;
protected ?DecorateActivity $decorateActivity = null;
abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;
abstract public function matchesCrmType(PlaybookCategory $category): bool;
abstract public function syncLead(string $crmId): ?Lead;
abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;
abstract public function createRecord(string $objectType, array $data): string;
abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;
/**
* Save an activity, update CRM prospect objects
*
* Create or update a task or event (depending on most applicable playbook)
*/
public function saveActivity(Activity $activity): Activity
{
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
throw new InvalidArgumentException('Please configure a Playbook first.');
}
$this->logger->info('[Salesforce] Log activity', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
]);
$payload = [
'OwnerId' => $this->profile->getCrmProviderId(),
'Description' => $this->getActivityDecorator()->generateDescription($activity),
];
$payload += $this->buildSubjectPayload($activity, $playbook);
$payload += $this->buildProspectPayload($activity);
$crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK
? Field::OBJECT_TASK
: Field::OBJECT_EVENT;
$this->logger->info('[Salesforce] Log activity. Payload Prepared', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
'crm_object_type' => $crmObjectType,
'payload' => $payload,
]);
$this->saveCrmObject($crmObjectType, $activity, $payload);
return $activity;
}
private function buildSubjectPayload(Activity $activity, Playbook $playbook): array
{
if ($this->matchesCrmType($activity->getCategory())) {
/**
* If the activity playbook category name (i.e. activity type) matches a known activity type that exists
* in the CRM, then we set the activity type in the payload.
* Some activity types may be locally created. They shouldn't be sent to Salesforce.
*
* The resulting payload attribute will look like:
* `Type` => 'Cold Call'
*/
return [
/** ActivityFieldID => ActivityType */
$playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),
'Subject' => $this->getActivityDecorator()->generateTitle($activity),
];
}
/**
* Building of the title seems very inconsistent
* Subject here will be something like:
* "Local activity type: Activity Title"
*/
$subject = $activity->getCategory()->getName();
if ($activity->getTitle() !== null) {
$subject .= ': ' . $activity->getTitle();
}
return ['Subject' => $subject];
}
private function buildProspectPayload(Activity $activity): array
{
$payload = [];
if ($activity->getAccountId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'account_id' => $activity->getAccountId(),
'opportunity_id' => $activity->getOpportunityId(),
'contact_id' => $activity->getContactId(),
]);
$hasLinkFeature = $this->crmHelperRepository->hasFeature(
$activity,
FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS
);
if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())
|| (! $hasLinkFeature && $activity->getOpportunityId())
) {
$payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();
} else {
$payload['WhatId'] = $activity->getAccount()->getCrmProviderId();
}
}
if ($activity->getContactId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'contact_id' => $activity->getContactId(),
]);
$payload['WhoId'] = $activity->getContact()->getCrmProviderId();
} elseif ($activity->getLeadId()) {
$this->logger->info('[Salesforce] Activity has lead id', [
'activity_id' => $activity->getId(),
'lead_id' => $activity->getLeadId(),
]);
/**
* An activity may have:
* a) a contact | account | opportunity (or combinations)
* b) only a lead
* c) none of the above
*
* An activity should not have a lead, and another prospect object at the same time.
*
* This logical flow should not happen naturally, but as a fallback: if an activity has both
* a Lead and an Account, the account's WhatId takes precedence in the CRM payload.
* The lead association will be detached locally, but the account WhatId is preserved in Salesforce.
*/
$payload += $this->handleActivityLead($activity);
}
return $payload;
}
private function handleActivityLead(Activity $activity): array
{
$this->logger->info('[Salesforce] Activity sync lead', [
'activity_id' => $activity->getId(),
]);
/**
* Sync lead to pull fresh data. Leads change often,
* they may get 'converted', and we must handle the new state accordingly
*/
try {
$activityLead = $this->syncLead(
$activity->getLead()->getCrmProviderId()
);
} catch (HttpNotFoundException) {
$this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not found, maybe it's remotely deleted
*/
$this->resetLeadAssociation($activity);
return [];
}
if ($activityLead === null) {
$this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not loaded, for some reason. It may be remotely found, but locally deleted.
* Or an important Lead property may be missing, and it cannot be fully imported.
*/
$this->resetLeadAssociation($activity);
return [];
}
/**
* The lead is not converted, directly use it as WhoId and move on.
*/
if ($activityLead->getConvertedAt() === null) {
return [
'WhoId' => $activity->getLead()->getCrmProviderId(),
'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.
];
}
/**
* Task/Event payload properties for the CRM update
*/
$whoId = null;
$whatId = null;
/**
* Activity payload properties, that need to be updated.
*/
$convertedOpportunityId = null;
$convertedAccountId = null;
$convertedContactId = null;
$value = null;
/**
* If there is converted opportunity, it will update the activity stage.
* If there isn't an opportunity, a converted account/contact cannot have a stage id,
* so the activity shouldn't have a stage either.
*/
$stageId = null;
/**
* The lead is definitely converted.
* This means the lead may be associated with an opportunity, account, or contact.
* The converted lead itself must be detached from the activity,
* while the converted prospect objects must be associated instead,
* since they now represent the state of the deal.
*/
$activity->setLeadId(null);
/**
* CRM property "WhatId" can be either an Opportunity or an Account.
* For us a converted Opportunity has higher priority than an Account.
* An Opportunity carries more concrete data, including a reference to the Account record itself.
*/
if ($activityLead->hasOpportunity()) {
$convertedOpportunity = $activityLead->getOpportunity();
$convertedOpportunityId = $convertedOpportunity->getId();
$convertedAccountId = $convertedOpportunity->getAccountId();
$stageId = $convertedOpportunity->getStageId();
$value = $convertedOpportunity->getValue();
$whatId = $convertedOpportunity->getCrmProviderId();
}
if ($activityLead->hasAccount()) {
$convertedAccount = $activityLead->getAccount();
$convertedAccountId ??= $convertedAccount->getId();
$whatId ??= $convertedAccount->getCrmProviderId();
}
/**
* WhoId can only be a Contact or a Lead.
* Since we are detaching the Lead, it can only be a Contact for the current activity.
* It does not conflict with any other object.
*/
if ($activityLead->hasContact()) {
$convertedContact = $activityLead->getContact();
$convertedContactId = $convertedContact->getId();
$whoId = $convertedContact->getCrmProviderId();
}
$activity->setOpportunityId($convertedOpportunityId);
$activity->setAccountId($convertedAccountId);
$activity->setContactId($convertedContactId);
$activity->setStageId($stageId);
$activity->setValue($value);
$activity->save();
$this->eventDispatcher->dispatch(
new ActivityLeadConverted($activity, $activityLead)
);
$this->logger->info('[Salesforce] Lead is converted', [
'activity_id' => $activity->getId(),
'whoId' => $whoId,
'whatId' => $whatId,
]);
return [
'WhoId' => $whoId,
'WhatId' => $whatId,
];
}
private function saveCrmObject(string $objectType, Activity $activity, array $payload): void
{
/**
* Tasks and events have different payload structures,
* so we need to consider the type of the object we are sending to the CRM
*/
$specificPayload = $objectType === Field::OBJECT_TASK
? $this->payloadBuilder->buildTaskPayload($activity)
: $this->payloadBuilder->buildEventPayload($activity);
$payload = array_merge($payload, $specificPayload);
if ($activity->hasCrmProviderId()) {
$this->logger->info('[Salesforce] Updating crm object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
try {
$this->updateCrmActivity($objectType, $activity, $payload);
} catch (HttpNotFoundException) {
$this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$activity->setCrmProviderId(null);
$activity->save();
}
return;
}
$this->logger->info('[Salesforce] Creating CRM object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$crmProviderId = $this->createRecord($objectType, $payload);
$activity->setCrmProviderId($crmProviderId);
$activity->save();
}
/**
* @throws HttpNotFoundException
*/
private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void
{
$sfActivity = $this->getRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
fields: ['Description', 'WhoId', 'WhatId']
);
if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {
$this->logger->info('[Salesforce] Updating WhoId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {
$this->logger->info('[Salesforce] Updating WhatId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
} else {
$payload['WhatId'] = null;
}
}
$payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(
$payload['Description'],
$sfActivity['Description'] ?? null
);
$this->logger->info('[Salesforce] Updating CRM activity data', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
'crmActivity' => $sfActivity,
'payload' => $payload,
]);
$this->updateRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
data: $payload
);
}
protected function getActivityDecorator(): DecorateActivity
{
if ($this->decorateActivity === null) {
$this->decorateActivity = app(DecorateActivity::class);
}
return $this->decorateActivity;
}
private function resetLeadAssociation(Activity $activity): void
{
$activity->setStageId(null);
$activity->setLeadId(null);
$activity->save();
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error
Next Highlighted Error
SELECT
# DISTINCT
opp.id as opp_id, opp.uuid, opp.name,
# COUNT(dr.id) AS deal_risk_count,
# dr.id,
# cfd.value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id
# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id
LEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 1
AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
GROUP BY opp.id, cfd.value
ORDER BY
# cfd.value
CAST(cfd.value AS UNSIGNED)
# owner_name
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1
# AND gdrt.is_enabled = 1)
DESC
LIMIT 25
# OFFSET 0
;
select * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';
select * from crm_layout_entities where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4584045;
SELECT * FROM crm_field_data WHERE object_id = 4584045;
SELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'
SELECT
opp.id as opportunity_id,
opp.name,
COUNT(dr.id) as risk_count
FROM opportunities opp
LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id
WHERE opp.id IN (
6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788
)
GROUP BY opp.id;
SELECT COUNT(dr.id)
FROM deal_risks dr
JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
WHERE dr.opportunity_id = 5563344
# AND gdrt.group_id = usr.group_id
EXPLAIN SELECT
opp.id as opp_id, opp.uuid, opp.name,
cfd.value,
cfv.sequence,
cfv.value,
# MAX(cfd.value) AS max_cfd_value,
usr.name AS owner_name,
opp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,
usr.uuid as owner_uuid,
usr.photo_path as owner_photo,
usr.id AS owner_id,
jt.name as owner_job,
opp.stage_id, opp.stage_updated_at,
acc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,
rt.business_process_id AS pipeline_id
FROM opportunities opp
LEFT JOIN record_types rt ON opp.record_type_id = rt.id
LEFT JOIN users usr ON opp.user_id = usr.id
LEFT JOIN accounts acc ON opp.account_id = acc.id
LEFT JOIN job_titles jt ON usr.job_title_id = jt.id
LEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id
FROM crm_field_data sub_cfd
WHERE sub_cfd.object_id = opp.id
AND sub_cfd.crm_field_id = 66810
ORDER BY sub_cfd.updated_at DESC
LIMIT 1)
LEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value
WHERE opp.user_id IS NOT NULL
AND opp.deleted_at IS NULL
AND opp.is_closed = 0
# AND opp.is_closed = 1
# AND opp.is_won = 0
AND opp.close_date >= '2024-01-01 00:00:00'
AND opp.close_date <= '2024-12-31 23:59:59'
AND usr.team_id = 1
# and opp.id = 4823179
# GROUP BY opp.id
ORDER BY
cfv.sequence DESC,
# opp.name
# owner_name
cfd.value
# CAST(cfd.value AS UNSIGNED)
# CAST(MAX(cfd.value) AS UNSIGNED)
# (SELECT COUNT(dr.id)
# FROM deal_risks dr
# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id
# WHERE dr.opportunity_id = opp.id
# AND dr.is_active = 1 AND gdrt.is_enabled = 1)
DESC
# LIMIT 75, 25
;
SELECT * FROM crm_field_values WHERE crm_field_id = 66810;
SELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at
FROM crm_fields f
INNER JOIN crm_field_data fd ON fd.crm_field_id = f.id
WHERE (f.crm_configuration_id = 1)
AND (f.object_type = 'opportunity')
# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))
AND (fd.object_id IN (4158460))
AND (f.crm_provider_id IN ('ForecastCategoryName'))
ORDER BY fd.object_id ASC, fd.updated_at DESC;
select * from crm_layouts where crm_configuration_id = 1;
select cf.* from crm_fields cf
join crm_layout_entities cle on cf.id = cle.crm_field_id
where crm_layout_id = 1493;
SELECT * FROM opportunities WHERE id = 4158460;
SELECT * FROM crm_field_data WHERE object_id = 4158460;
select * from users where team_id = 1;
SELECT * FROM users WHERE id = 7160;
select * from role_user where user_id = 3248;
select * from crm_field_values where crm_field_id = 66824;
SELECT * FROM users WHERE id = 23470;
select * from crm_configurations;
# [PASSWORD_DOTS]
select * from teams where id = 1038; # 23521, 966
select * from users where team_id = 1038;
select * from crm_configurations where id = 966;
SELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762
SELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764
SELECT * FROM participants WHERE activity_id = 54965764;
SELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075
SELECT * FROM participants WHERE activity_id = 54964075;
select f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id
where tf.team_id = 1038;
# [PASSWORD_DOTS] PD [PASSWORD_DOTS]
select * from teams where id = 1029;
SELECT * FROM crm_configurations WHERE id = 957;
SELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421
# [PASSWORD_DOTS] Close [PASSWORD_DOTS]
select * from teams where id = 1031;
SELECT * FROM crm_configurations WHERE id = 959;
SELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517
SELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433
SELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009
# [PASSWORD_DOTS] SF [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;
select * from roles;
select * from permissions;
select * from permission_role where permission_id = 136;
select * from migrations order by id desc;
select * from teams where id IN (1, 1037);
select * from crm_layouts where crm_configuration_id = 1;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;
SELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);
select * from features;
select * from team_features where feature_id = 33;
select * from opportunities;
select * from teams;
SELECT
CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,
u.email,
sa.*,
t.owner_id FROM social_accounts sa
JOIN users u on u.id = sa.sociable_id
JOIN teams t on t.id = u.team_id
WHERE u.team_id = 1052 and sa.provider = 'hubspot';
SELECT * FROM accounts where id = 11512582;
select * from activities where account_id = 11512582;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
45270
|
NULL
|
NULL
|
NULL
|
|
45273
|
1623
|
17
|
2026-05-14T14:28:14.657125+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768894657_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
pdser
ParticipantData.php .../app/Models/Activity/ParticipantData.php, class...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project Files","depth":2,"bounds":{"left":0.8298611,"top":0.25,"width":0.07430556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"pdser","depth":1,"bounds":{"left":0.50555557,"top":0.29222223,"width":0.45277777,"height":0.032222223},"on_screen":true,"value":"pdser","role_description":"text field","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"ParticipantData.php .../app/Models/Activity/ParticipantData.php, class","depth":2,"role_description":"text"}]...
|
-8450185282525829171
|
-8495382113397430364
|
visual_change
|
accessibility
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
pdser
ParticipantData.php .../app/Models/Activity/ParticipantData.php, class...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45274
|
1623
|
18
|
2026-05-14T14:28:17.700377+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768897700_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
All Places
Preview
Filter
Open in Find Tool Window All Places
Preview
Filter
Open in Find Tool Window
curl --location 'https://api.hubapi.com/crm/v3/objects/contacts/search' \ --header 'Content-Type: application/json' \ --header 'Authorization: [AUTH_TOKEN]' \ --data '{ "limit": 1 }'
Models/Activity/ParticipantData.php
Open In Right Split...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"All Places","depth":2,"bounds":{"left":0.8423611,"top":0.25,"width":0.061805554,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"curl --location 'https://api.hubapi.com/crm/v3/objects/contacts/search' \\ --header 'Content-Type: application/json' \\ --header 'Authorization: Bearer CIKvma3iMxIZQlNQMl8kQEwrAgwACAkUAhIJBB4BAQEDBxjVrJYMILuP6SAo1KwCMhTHn-y3_hxt0uPnjMvPqUYCkHSMaToyQlNQMl8kQEwrAiUACBkGawEFThwBARIBAQEEATEEAQEBAQEBAQEBAQUBEggBAQEBAYlCFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA' \\ --data '{ \"limit\": 1 }'","depth":1,"bounds":{"left":0.50555557,"top":0.29222223,"width":0.45277777,"height":0.032222223},"on_screen":true,"value":"curl --location 'https://api.hubapi.com/crm/v3/objects/contacts/search' \\ --header 'Content-Type: application/json' \\ --header 'Authorization: Bearer CIKvma3iMxIZQlNQMl8kQEwrAgwACAkUAhIJBB4BAQEDBxjVrJYMILuP6SAo1KwCMhTHn-y3_hxt0uPnjMvPqUYCkHSMaToyQlNQMl8kQEwrAiUACBkGawEFThwBARIBAQEEATEEAQEBAQEBAQEBAQUBEggBAQEBAYlCFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA' \\ --data '{ \"limit\": 1 }'","role_description":"text field","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Models/Activity/ParticipantData.php","depth":1,"bounds":{"left":0.51319444,"top":0.74777776,"width":0.14166667,"height":0.018888889},"on_screen":true,"help_text":"Models/Activity/ParticipantData.php","role_description":"text"},{"role":"AXLink","text":"Open In Right Split","depth":1,"bounds":{"left":0.8673611,"top":0.74777776,"width":0.08055556,"height":0.018888889},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-4208526946439215642
|
3176045449282790043
|
visual_change
|
accessibility
|
NULL
|
All Places
Preview
Filter
Open in Find Tool Window All Places
Preview
Filter
Open in Find Tool Window
curl --location 'https://api.hubapi.com/crm/v3/objects/contacts/search' \ --header 'Content-Type: application/json' \ --header 'Authorization: [AUTH_TOKEN]' \ --data '{ "limit": 1 }'
Models/Activity/ParticipantData.php
Open In Right Split...
|
45273
|
NULL
|
NULL
|
NULL
|
|
45275
|
1623
|
19
|
2026-05-14T14:28:26.829403+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768906829_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
pd
ParticipantData.php .../app/Models/Activity/ParticipantData.php, class
ParticipantDeclinedRecordingEvent.php .../.../Conferences/ParticipantDeclinedRecordingEvent.php, class
ParticipantDeclinedRecordingListener.php .../.../Conferences/ParticipantDeclinedRecordingListener.php, final class
ParticipantDeclinedRecordingTest.php .../.../Events/Activities/ParticipantDeclinedRecordingTest.php, final class
ParticipantDeclinedRecordingTest.php .../.../Activities/ParticipantDeclinedRecordingTest.php, final class
PayloadDatabaseHydratorAbstract.php .../.../LiveFeed/Hydrator/PayloadDatabaseHydratorAbstract.php, abstract class
PurgeDeletedOpportunitiesCommand.php .../.../Crm/PurgeDeletedOpportunitiesCommand.php, class
ParticipantDeclinedRecording.php .../app/Notifications/Activities/ParticipantDeclinedRecording.php, class
PipedriveDefaultStrategy.php .../app/.../Pipedrive/ProspectSearchStrategy/PipedriveDefaultStrategy.php, class
ProphetDealCrmFieldValuesServiceTest.php .../ProphetDealCrmFieldValuesServiceTest.php, class
ProphetDealCrmFieldValuesService.php .../ProphetDealCrmFieldValuesService.php, class
ParticipantData.php.html build/coverage/Models/Activity
ParticipantDeclinedRecording.php.html build/coverage/Notifications/Activities
PipedriveDefaultStrategy.php.html build/coverage/Services/Crm/Pipedrive/ProspectSearchStrategy
PayloadDatabaseHydratorAbstract.php.html build/coverage/Component/LiveFeed/Hydrator
… more
ParticipantData.php .../app/Models/Activity/ParticipantData.php, class
ParticipantDeclinedRecordingEvent.php .../.../Conferences/ParticipantDeclinedRecordingEvent.php, class
ParticipantDeclinedRecordingListener.php .../.../Conferences/ParticipantDeclinedRecordingListener.php, final class
ParticipantDeclinedRecordingTest.php .../.../Events/Activities/ParticipantDeclinedRecordingTest.php, final class
ParticipantDeclinedRecordingTest.php .../.../Activities/ParticipantDeclinedRecordingTest.php, final class
PayloadDatabaseHydratorAbstract.php .../.../LiveFeed/Hydrator/PayloadDatabaseHydratorAbstract.php, abstract class
PurgeDeletedOpportunitiesCommand.php .../.../Crm/PurgeDeletedOpportunitiesCommand.php, class
ParticipantDeclinedRecording.php .../app/Notifications/Activities/ParticipantDeclinedRecording.php, class
PipedriveDefaultStrategy.php .../app/.../Pipedrive/ProspectSearchStrategy/PipedriveDefaultStrategy.php, class
ProphetDealCrmFieldValuesServiceTest.php .../ProphetDealCrmFieldValuesServiceTest.php, class
ProphetDealCrmFieldValuesService.php .../ProphetDealCrmFieldValuesService.php, class
ParticipantData.php.html build/coverage/Models/Activity
ParticipantDeclinedRecording.php.html build/coverage/Notifications/Activities
PipedriveDefaultStrategy.php.html build/coverage/Services/Crm/Pipedrive/ProspectSearchStrategy
PayloadDatabaseHydratorAbstract.php.html build/coverage/Component/LiveFeed/Hydrator
… more
Models/Activity/ParticipantData.php
Open In Right Split...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project Files","depth":2,"bounds":{"left":0.8298611,"top":0.25,"width":0.07430556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"pd","depth":1,"bounds":{"left":0.50555557,"top":0.29222223,"width":0.45277777,"height":0.032222223},"on_screen":true,"value":"pd","role_description":"text field","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"ParticipantData.php .../app/Models/Activity/ParticipantData.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingEvent.php .../.../Conferences/ParticipantDeclinedRecordingEvent.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingListener.php .../.../Conferences/ParticipantDeclinedRecordingListener.php, final class","depth":2,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingTest.php .../.../Events/Activities/ParticipantDeclinedRecordingTest.php, final class","depth":2,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingTest.php .../.../Activities/ParticipantDeclinedRecordingTest.php, final class","depth":2,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PayloadDatabaseHydratorAbstract.php .../.../LiveFeed/Hydrator/PayloadDatabaseHydratorAbstract.php, abstract class","depth":2,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PurgeDeletedOpportunitiesCommand.php .../.../Crm/PurgeDeletedOpportunitiesCommand.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecording.php .../app/Notifications/Activities/ParticipantDeclinedRecording.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PipedriveDefaultStrategy.php .../app/.../Pipedrive/ProspectSearchStrategy/PipedriveDefaultStrategy.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ProphetDealCrmFieldValuesServiceTest.php .../ProphetDealCrmFieldValuesServiceTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ProphetDealCrmFieldValuesService.php .../ProphetDealCrmFieldValuesService.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantData.php.html build/coverage/Models/Activity","depth":2,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecording.php.html build/coverage/Notifications/Activities","depth":2,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PipedriveDefaultStrategy.php.html build/coverage/Services/Crm/Pipedrive/ProspectSearchStrategy","depth":2,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PayloadDatabaseHydratorAbstract.php.html build/coverage/Component/LiveFeed/Hydrator","depth":2,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"… more","depth":2,"bounds":{"left":0.49930555,"top":0.7033333,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantData.php .../app/Models/Activity/ParticipantData.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingEvent.php .../.../Conferences/ParticipantDeclinedRecordingEvent.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingListener.php .../.../Conferences/ParticipantDeclinedRecordingListener.php, final class","depth":4,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingTest.php .../.../Events/Activities/ParticipantDeclinedRecordingTest.php, final class","depth":4,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecordingTest.php .../.../Activities/ParticipantDeclinedRecordingTest.php, final class","depth":4,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PayloadDatabaseHydratorAbstract.php .../.../LiveFeed/Hydrator/PayloadDatabaseHydratorAbstract.php, abstract class","depth":4,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PurgeDeletedOpportunitiesCommand.php .../.../Crm/PurgeDeletedOpportunitiesCommand.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecording.php .../app/Notifications/Activities/ParticipantDeclinedRecording.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PipedriveDefaultStrategy.php .../app/.../Pipedrive/ProspectSearchStrategy/PipedriveDefaultStrategy.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ProphetDealCrmFieldValuesServiceTest.php .../ProphetDealCrmFieldValuesServiceTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ProphetDealCrmFieldValuesService.php .../ProphetDealCrmFieldValuesService.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantData.php.html build/coverage/Models/Activity","depth":4,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ParticipantDeclinedRecording.php.html build/coverage/Notifications/Activities","depth":4,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PipedriveDefaultStrategy.php.html build/coverage/Services/Crm/Pipedrive/ProspectSearchStrategy","depth":4,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"PayloadDatabaseHydratorAbstract.php.html build/coverage/Component/LiveFeed/Hydrator","depth":4,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"… more","depth":4,"bounds":{"left":0.49930555,"top":0.7033333,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Models/Activity/ParticipantData.php","depth":1,"bounds":{"left":0.51319444,"top":0.74777776,"width":0.14166667,"height":0.018888889},"on_screen":true,"help_text":"Models/Activity/ParticipantData.php","role_description":"text"},{"role":"AXLink","text":"Open In Right Split","depth":1,"bounds":{"left":0.8673611,"top":0.74777776,"width":0.08055556,"height":0.018888889},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7949182917671715439
|
7627209731114379089
|
visual_change
|
accessibility
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
pd
ParticipantData.php .../app/Models/Activity/ParticipantData.php, class
ParticipantDeclinedRecordingEvent.php .../.../Conferences/ParticipantDeclinedRecordingEvent.php, class
ParticipantDeclinedRecordingListener.php .../.../Conferences/ParticipantDeclinedRecordingListener.php, final class
ParticipantDeclinedRecordingTest.php .../.../Events/Activities/ParticipantDeclinedRecordingTest.php, final class
ParticipantDeclinedRecordingTest.php .../.../Activities/ParticipantDeclinedRecordingTest.php, final class
PayloadDatabaseHydratorAbstract.php .../.../LiveFeed/Hydrator/PayloadDatabaseHydratorAbstract.php, abstract class
PurgeDeletedOpportunitiesCommand.php .../.../Crm/PurgeDeletedOpportunitiesCommand.php, class
ParticipantDeclinedRecording.php .../app/Notifications/Activities/ParticipantDeclinedRecording.php, class
PipedriveDefaultStrategy.php .../app/.../Pipedrive/ProspectSearchStrategy/PipedriveDefaultStrategy.php, class
ProphetDealCrmFieldValuesServiceTest.php .../ProphetDealCrmFieldValuesServiceTest.php, class
ProphetDealCrmFieldValuesService.php .../ProphetDealCrmFieldValuesService.php, class
ParticipantData.php.html build/coverage/Models/Activity
ParticipantDeclinedRecording.php.html build/coverage/Notifications/Activities
PipedriveDefaultStrategy.php.html build/coverage/Services/Crm/Pipedrive/ProspectSearchStrategy
PayloadDatabaseHydratorAbstract.php.html build/coverage/Component/LiveFeed/Hydrator
… more
ParticipantData.php .../app/Models/Activity/ParticipantData.php, class
ParticipantDeclinedRecordingEvent.php .../.../Conferences/ParticipantDeclinedRecordingEvent.php, class
ParticipantDeclinedRecordingListener.php .../.../Conferences/ParticipantDeclinedRecordingListener.php, final class
ParticipantDeclinedRecordingTest.php .../.../Events/Activities/ParticipantDeclinedRecordingTest.php, final class
ParticipantDeclinedRecordingTest.php .../.../Activities/ParticipantDeclinedRecordingTest.php, final class
PayloadDatabaseHydratorAbstract.php .../.../LiveFeed/Hydrator/PayloadDatabaseHydratorAbstract.php, abstract class
PurgeDeletedOpportunitiesCommand.php .../.../Crm/PurgeDeletedOpportunitiesCommand.php, class
ParticipantDeclinedRecording.php .../app/Notifications/Activities/ParticipantDeclinedRecording.php, class
PipedriveDefaultStrategy.php .../app/.../Pipedrive/ProspectSearchStrategy/PipedriveDefaultStrategy.php, class
ProphetDealCrmFieldValuesServiceTest.php .../ProphetDealCrmFieldValuesServiceTest.php, class
ProphetDealCrmFieldValuesService.php .../ProphetDealCrmFieldValuesService.php, class
ParticipantData.php.html build/coverage/Models/Activity
ParticipantDeclinedRecording.php.html build/coverage/Notifications/Activities
PipedriveDefaultStrategy.php.html build/coverage/Services/Crm/Pipedrive/ProspectSearchStrategy
PayloadDatabaseHydratorAbstract.php.html build/coverage/Component/LiveFeed/Hydrator
… more
Models/Activity/ParticipantData.php
Open In Right Split...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45277
|
1623
|
20
|
2026-05-14T14:28:39.010729+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768919010_m1.jpg...
|
PhpStorm
|
faVsco.js – LogActivityTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3772723929611228661
|
-6979379262459376693
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
PhpStorm•Project vFileFV faVsco.jsvEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl* #12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTestv100% C8• Thu 14 May 17:28:38* :Q+,•х:-© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© RemoteSearch.php© Service.phpT LogActivityTrait.php X© PlainTextDecorateActivity.php© ActivityPlaybookTrait.php© CrmHelperRepository.php© Service.php© AccountController.phpT IntegrationAppTrait.php.env.staging18E.env© DetachActivityObject.phpv C Listeners© ConvertLeadActivities.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpHubspotPaginationService.php© PurgeLookupCache.php› D Metadata> C Migration© HandleHubspotRateLimit.php15.04.26 Vasilev15.04.26 Vasilevv Pipedrive> D OpportunitySyncStrategy15.04.26lVasilev> D ProspectSearchStrategy15.04.26 Vasilev© ApiFields.php27.04.26 Vasilev© Client.php27.04.26 Vasilev© FieldDefinitions.php27.04.26 Vasilev© PipedriveApiClient.php27.04.26 Vasilev© PipedriveApiException.php27.04.26 Vasilev© Service.php15.04.26 Vasilev© TokenStorage.php23.04.26 Vasilevv D Salesforce20.04.26 Vasilev> C Fields15.04.26 Vasilev> OpportunityMatcher15.04.26 Vasilev0 OpportunitySyncStrategy23.04.26 VasilevProspectSearchStrategy23.04.26 VasilevD ServiceTraits23.04.26 VasilevT BatchSyncTrait.php23.04.26 VasilevT FollowupActivityTrait.php23.04.26 VasilevD LogActivityTrait.php23.04.26 VasilevT RecordManipulationsTrai23.04.26 VasilevT SyncFieldsTrait.php27.04.26 Vasilev© Client.php27.04.26 Vasilev© DecorateActivity.php27.04.26 VasilevDeleteObjectsTrait.php27.04.26 Vasilev© FieldDefinitions.php27.04.26 Vasilev© PavinadRuilder nhn27.04.26 Vasilev trait LogActivityTraitpublic function saveActivity(Activity $activity): ActivityВ6 м1 ^$this->logger->info('[Salesforce] Log activity', l'activity_id' => Sactivity->getId(),'object_type' => $playbook->getActivityType(),1):Spayload = ['OwnerId'=> $this-›profile->getCrmProviderId(,'Description' => $this->getActivityDecorator()->generateDescription($activity),]:$payload += Sthis->buildSubjectPayload(Sactivity, $playbook);$payload += $this->buildProspectPayLoad(Sactivity):$crmObjectType = $playbook->getActivityType() === Playbook: :ACTIVITY_TYPE_TASK? Field::0BJECT_TASK: Field::0BJECT_EVENT;$this->logger->info('[Salesforce] Log activity. Payload Prepared', ['activity_id' => Sactivity->getId(),'object_type' => $playbook->getActivityType().'crm_object_type' => $crm0bjectType,'payload' => $payload,1):Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=custom.log=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D — 232233 V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASEWHENidFROMsocial,1 on u.id= sa.:1..n<->1: on t.L_id = 1052 andIMaccounts wheiactivities63:56UTF-8Co 4 spaces...
|
45275
|
NULL
|
NULL
|
NULL
|
|
45276
|
1624
|
13
|
2026-05-14T14:28:40.004583+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768920004_m2.jpg...
|
PhpStorm
|
faVsco.js – LogActivityTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
6
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Salesforce\ServiceTraits;
use Illuminate\Events\Dispatcher;
use Jiminny\Events\Activities\Crm\ActivityLeadConverted;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Feature\FeatureEnum;
use Jiminny\Models\Lead;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Services\Crm\Helpers\CrmHelperRepository;
use Jiminny\Services\Crm\Salesforce\DecorateActivity;
use Jiminny\Services\Crm\Salesforce\PayloadBuilder;
use Psr\Log\LoggerInterface;
trait LogActivityTrait
{
public ?Configuration $config;
public ?Profile $profile;
protected PayloadBuilder $payloadBuilder;
protected LoggerInterface $logger;
protected Dispatcher $eventDispatcher;
protected CrmHelperRepository $crmHelperRepository;
protected ?DecorateActivity $decorateActivity = null;
abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;
abstract public function matchesCrmType(PlaybookCategory $category): bool;
abstract public function syncLead(string $crmId): ?Lead;
abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;
abstract public function createRecord(string $objectType, array $data): string;
abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;
/**
* Save an activity, update CRM prospect objects
*
* Create or update a task or event (depending on most applicable playbook)
*/
public function saveActivity(Activity $activity): Activity
{
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
throw new InvalidArgumentException('Please configure a Playbook first.');
}
$this->logger->info('[Salesforce] Log activity', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
]);
$payload = [
'OwnerId' => $this->profile->getCrmProviderId(),
'Description' => $this->getActivityDecorator()->generateDescription($activity),
];
$payload += $this->buildSubjectPayload($activity, $playbook);
$payload += $this->buildProspectPayload($activity);
$crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK
? Field::OBJECT_TASK
: Field::OBJECT_EVENT;
$this->logger->info('[Salesforce] Log activity. Payload Prepared', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
'crm_object_type' => $crmObjectType,
'payload' => $payload,
]);
$this->saveCrmObject($crmObjectType, $activity, $payload);
return $activity;
}
private function buildSubjectPayload(Activity $activity, Playbook $playbook): array
{
if ($this->matchesCrmType($activity->getCategory())) {
/**
* If the activity playbook category name (i.e. activity type) matches a known activity type that exists
* in the CRM, then we set the activity type in the payload.
* Some activity types may be locally created. They shouldn't be sent to Salesforce.
*
* The resulting payload attribute will look like:
* `Type` => 'Cold Call'
*/
return [
/** ActivityFieldID => ActivityType */
$playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),
'Subject' => $this->getActivityDecorator()->generateTitle($activity),
];
}
/**
* Building of the title seems very inconsistent
* Subject here will be something like:
* "Local activity type: Activity Title"
*/
$subject = $activity->getCategory()->getName();
if ($activity->getTitle() !== null) {
$subject .= ': ' . $activity->getTitle();
}
return ['Subject' => $subject];
}
private function buildProspectPayload(Activity $activity): array
{
$payload = [];
if ($activity->getAccountId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'account_id' => $activity->getAccountId(),
'opportunity_id' => $activity->getOpportunityId(),
'contact_id' => $activity->getContactId(),
]);
$hasLinkFeature = $this->crmHelperRepository->hasFeature(
$activity,
FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS
);
if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())
|| (! $hasLinkFeature && $activity->getOpportunityId())
) {
$payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();
} else {
$payload['WhatId'] = $activity->getAccount()->getCrmProviderId();
}
}
if ($activity->getContactId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'contact_id' => $activity->getContactId(),
]);
$payload['WhoId'] = $activity->getContact()->getCrmProviderId();
} elseif ($activity->getLeadId()) {
$this->logger->info('[Salesforce] Activity has lead id', [
'activity_id' => $activity->getId(),
'lead_id' => $activity->getLeadId(),
]);
/**
* An activity may have:
* a) a contact | account | opportunity (or combinations)
* b) only a lead
* c) none of the above
*
* An activity should not have a lead, and another prospect object at the same time.
*
* This logical flow should not happen naturally, but as a fallback: if an activity has both
* a Lead and an Account, the account's WhatId takes precedence in the CRM payload.
* The lead association will be detached locally, but the account WhatId is preserved in Salesforce.
*/
$payload += $this->handleActivityLead($activity);
}
return $payload;
}
private function handleActivityLead(Activity $activity): array
{
$this->logger->info('[Salesforce] Activity sync lead', [
'activity_id' => $activity->getId(),
]);
/**
* Sync lead to pull fresh data. Leads change often,
* they may get 'converted', and we must handle the new state accordingly
*/
try {
$activityLead = $this->syncLead(
$activity->getLead()->getCrmProviderId()
);
} catch (HttpNotFoundException) {
$this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not found, maybe it's remotely deleted
*/
$this->resetLeadAssociation($activity);
return [];
}
if ($activityLead === null) {
$this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not loaded, for some reason. It may be remotely found, but locally deleted.
* Or an important Lead property may be missing, and it cannot be fully imported.
*/
$this->resetLeadAssociation($activity);
return [];
}
/**
* The lead is not converted, directly use it as WhoId and move on.
*/
if ($activityLead->getConvertedAt() === null) {
return [
'WhoId' => $activity->getLead()->getCrmProviderId(),
'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.
];
}
/**
* Task/Event payload properties for the CRM update
*/
$whoId = null;
$whatId = null;
/**
* Activity payload properties, that need to be updated.
*/
$convertedOpportunityId = null;
$convertedAccountId = null;
$convertedContactId = null;
$value = null;
/**
* If there is converted opportunity, it will update the activity stage.
* If there isn't an opportunity, a converted account/contact cannot have a stage id,
* so the activity shouldn't have a stage either.
*/
$stageId = null;
/**
* The lead is definitely converted.
* This means the lead may be associated with an opportunity, account, or contact.
* The converted lead itself must be detached from the activity,
* while the converted prospect objects must be associated instead,
* since they now represent the state of the deal.
*/
$activity->setLeadId(null);
/**
* CRM property "WhatId" can be either an Opportunity or an Account.
* For us a converted Opportunity has higher priority than an Account.
* An Opportunity carries more concrete data, including a reference to the Account record itself.
*/
if ($activityLead->hasOpportunity()) {
$convertedOpportunity = $activityLead->getOpportunity();
$convertedOpportunityId = $convertedOpportunity->getId();
$convertedAccountId = $convertedOpportunity->getAccountId();
$stageId = $convertedOpportunity->getStageId();
$value = $convertedOpportunity->getValue();
$whatId = $convertedOpportunity->getCrmProviderId();
}
if ($activityLead->hasAccount()) {
$convertedAccount = $activityLead->getAccount();
$convertedAccountId ??= $convertedAccount->getId();
$whatId ??= $convertedAccount->getCrmProviderId();
}
/**
* WhoId can only be a Contact or a Lead.
* Since we are detaching the Lead, it can only be a Contact for the current activity.
* It does not conflict with any other object.
*/
if ($activityLead->hasContact()) {
$convertedContact = $activityLead->getContact();
$convertedContactId = $convertedContact->getId();
$whoId = $convertedContact->getCrmProviderId();
}
$activity->setOpportunityId($convertedOpportunityId);
$activity->setAccountId($convertedAccountId);
$activity->setContactId($convertedContactId);
$activity->setStageId($stageId);
$activity->setValue($value);
$activity->save();
$this->eventDispatcher->dispatch(
new ActivityLeadConverted($activity, $activityLead)
);
$this->logger->info('[Salesforce] Lead is converted', [
'activity_id' => $activity->getId(),
'whoId' => $whoId,
'whatId' => $whatId,
]);
return [
'WhoId' => $whoId,
'WhatId' => $whatId,
];
}
private function saveCrmObject(string $objectType, Activity $activity, array $payload): void
{
/**
* Tasks and events have different payload structures,
* so we need to consider the type of the object we are sending to the CRM
*/
$specificPayload = $objectType === Field::OBJECT_TASK
? $this->payloadBuilder->buildTaskPayload($activity)
: $this->payloadBuilder->buildEventPayload($activity);
$payload = array_merge($payload, $specificPayload);
if ($activity->hasCrmProviderId()) {
$this->logger->info('[Salesforce] Updating crm object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
try {
$this->updateCrmActivity($objectType, $activity, $payload);
} catch (HttpNotFoundException) {
$this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$activity->setCrmProviderId(null);
$activity->save();
}
return;
}
$this->logger->info('[Salesforce] Creating CRM object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$crmProviderId = $this->createRecord($objectType, $payload);
$activity->setCrmProviderId($crmProviderId);
$activity->save();
}
/**
* @throws HttpNotFoundException
*/
private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void
{
$sfActivity = $this->getRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
fields: ['Description', 'WhoId', 'WhatId']
);
if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {
$this->logger->info('[Salesforce] Updating WhoId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {
$this->logger->info('[Salesforce] Updating WhatId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
} else {
$payload['WhatId'] = null;
}
}
$payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(
$payload['Description'],
$sfActivity['Description'] ?? null
);
$this->logger->info('[Salesforce] Updating CRM activity data', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
'crmActivity' => $sfActivity,
'payload' => $payload,
]);
$this->updateRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
data: $payload
);
}
protected function getActivityDecorator(): DecorateActivity
{
if ($this->decorateActivity === null) {
$this->decorateActivity = app(DecorateActivity::class);
}
return $this->decorateActivity;
}
private function resetLeadAssociation(Activity $activity): void
{
$activity->setStageId(null);
$activity->setLeadId(null);
$activity->save();
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"6","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits;\n\nuse Illuminate\\Events\\Dispatcher;\nuse Jiminny\\Events\\Activities\\Crm\\ActivityLeadConverted;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Feature\\FeatureEnum;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Services\\Crm\\Helpers\\CrmHelperRepository;\nuse Jiminny\\Services\\Crm\\Salesforce\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Salesforce\\PayloadBuilder;\nuse Psr\\Log\\LoggerInterface;\n\ntrait LogActivityTrait\n{\n public ?Configuration $config;\n public ?Profile $profile;\n\n protected PayloadBuilder $payloadBuilder;\n protected LoggerInterface $logger;\n protected Dispatcher $eventDispatcher;\n protected CrmHelperRepository $crmHelperRepository;\n protected ?DecorateActivity $decorateActivity = null;\n\n abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;\n abstract public function matchesCrmType(PlaybookCategory $category): bool;\n\n abstract public function syncLead(string $crmId): ?Lead;\n abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;\n abstract public function createRecord(string $objectType, array $data): string;\n abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;\n\n /**\n * Save an activity, update CRM prospect objects\n *\n * Create or update a task or event (depending on most applicable playbook)\n */\n public function saveActivity(Activity $activity): Activity\n {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n throw new InvalidArgumentException('Please configure a Playbook first.');\n }\n\n $this->logger->info('[Salesforce] Log activity', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n ]);\n\n $payload = [\n 'OwnerId' => $this->profile->getCrmProviderId(),\n 'Description' => $this->getActivityDecorator()->generateDescription($activity),\n ];\n\n $payload += $this->buildSubjectPayload($activity, $playbook);\n $payload += $this->buildProspectPayload($activity);\n\n $crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK\n ? Field::OBJECT_TASK\n : Field::OBJECT_EVENT;\n\n $this->logger->info('[Salesforce] Log activity. Payload Prepared', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n 'crm_object_type' => $crmObjectType,\n 'payload' => $payload,\n ]);\n\n $this->saveCrmObject($crmObjectType, $activity, $payload);\n\n return $activity;\n }\n\n private function buildSubjectPayload(Activity $activity, Playbook $playbook): array\n {\n if ($this->matchesCrmType($activity->getCategory())) {\n /**\n * If the activity playbook category name (i.e. activity type) matches a known activity type that exists\n * in the CRM, then we set the activity type in the payload.\n * Some activity types may be locally created. They shouldn't be sent to Salesforce.\n *\n * The resulting payload attribute will look like:\n * `Type` => 'Cold Call'\n */\n return [\n /** ActivityFieldID => ActivityType */\n $playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),\n 'Subject' => $this->getActivityDecorator()->generateTitle($activity),\n ];\n }\n\n /**\n * Building of the title seems very inconsistent\n * Subject here will be something like:\n * \"Local activity type: Activity Title\"\n */\n $subject = $activity->getCategory()->getName();\n if ($activity->getTitle() !== null) {\n $subject .= ': ' . $activity->getTitle();\n }\n\n return ['Subject' => $subject];\n }\n\n private function buildProspectPayload(Activity $activity): array\n {\n $payload = [];\n\n if ($activity->getAccountId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'account_id' => $activity->getAccountId(),\n 'opportunity_id' => $activity->getOpportunityId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $hasLinkFeature = $this->crmHelperRepository->hasFeature(\n $activity,\n FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS\n );\n\n if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())\n || (! $hasLinkFeature && $activity->getOpportunityId())\n ) {\n $payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();\n } else {\n $payload['WhatId'] = $activity->getAccount()->getCrmProviderId();\n }\n }\n\n if ($activity->getContactId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $payload['WhoId'] = $activity->getContact()->getCrmProviderId();\n } elseif ($activity->getLeadId()) {\n $this->logger->info('[Salesforce] Activity has lead id', [\n 'activity_id' => $activity->getId(),\n 'lead_id' => $activity->getLeadId(),\n ]);\n\n /**\n * An activity may have:\n * a) a contact | account | opportunity (or combinations)\n * b) only a lead\n * c) none of the above\n *\n * An activity should not have a lead, and another prospect object at the same time.\n *\n * This logical flow should not happen naturally, but as a fallback: if an activity has both\n * a Lead and an Account, the account's WhatId takes precedence in the CRM payload.\n * The lead association will be detached locally, but the account WhatId is preserved in Salesforce.\n */\n $payload += $this->handleActivityLead($activity);\n }\n\n return $payload;\n }\n\n private function handleActivityLead(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Activity sync lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Sync lead to pull fresh data. Leads change often,\n * they may get 'converted', and we must handle the new state accordingly\n */\n try {\n $activityLead = $this->syncLead(\n $activity->getLead()->getCrmProviderId()\n );\n } catch (HttpNotFoundException) {\n $this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not found, maybe it's remotely deleted\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n if ($activityLead === null) {\n $this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not loaded, for some reason. It may be remotely found, but locally deleted.\n * Or an important Lead property may be missing, and it cannot be fully imported.\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n /**\n * The lead is not converted, directly use it as WhoId and move on.\n */\n if ($activityLead->getConvertedAt() === null) {\n return [\n 'WhoId' => $activity->getLead()->getCrmProviderId(),\n 'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.\n ];\n }\n\n /**\n * Task/Event payload properties for the CRM update\n */\n $whoId = null;\n $whatId = null;\n\n /**\n * Activity payload properties, that need to be updated.\n */\n $convertedOpportunityId = null;\n $convertedAccountId = null;\n $convertedContactId = null;\n $value = null;\n\n /**\n * If there is converted opportunity, it will update the activity stage.\n * If there isn't an opportunity, a converted account/contact cannot have a stage id,\n * so the activity shouldn't have a stage either.\n */\n $stageId = null;\n\n /**\n * The lead is definitely converted.\n * This means the lead may be associated with an opportunity, account, or contact.\n * The converted lead itself must be detached from the activity,\n * while the converted prospect objects must be associated instead,\n * since they now represent the state of the deal.\n */\n $activity->setLeadId(null);\n\n /**\n * CRM property \"WhatId\" can be either an Opportunity or an Account.\n * For us a converted Opportunity has higher priority than an Account.\n * An Opportunity carries more concrete data, including a reference to the Account record itself.\n */\n if ($activityLead->hasOpportunity()) {\n $convertedOpportunity = $activityLead->getOpportunity();\n\n $convertedOpportunityId = $convertedOpportunity->getId();\n $convertedAccountId = $convertedOpportunity->getAccountId();\n $stageId = $convertedOpportunity->getStageId();\n $value = $convertedOpportunity->getValue();\n\n $whatId = $convertedOpportunity->getCrmProviderId();\n }\n\n if ($activityLead->hasAccount()) {\n $convertedAccount = $activityLead->getAccount();\n\n $convertedAccountId ??= $convertedAccount->getId();\n\n $whatId ??= $convertedAccount->getCrmProviderId();\n }\n\n /**\n * WhoId can only be a Contact or a Lead.\n * Since we are detaching the Lead, it can only be a Contact for the current activity.\n * It does not conflict with any other object.\n */\n if ($activityLead->hasContact()) {\n $convertedContact = $activityLead->getContact();\n\n $convertedContactId = $convertedContact->getId();\n\n $whoId = $convertedContact->getCrmProviderId();\n }\n\n $activity->setOpportunityId($convertedOpportunityId);\n $activity->setAccountId($convertedAccountId);\n $activity->setContactId($convertedContactId);\n $activity->setStageId($stageId);\n $activity->setValue($value);\n\n $activity->save();\n\n $this->eventDispatcher->dispatch(\n new ActivityLeadConverted($activity, $activityLead)\n );\n\n $this->logger->info('[Salesforce] Lead is converted', [\n 'activity_id' => $activity->getId(),\n 'whoId' => $whoId,\n 'whatId' => $whatId,\n ]);\n\n return [\n 'WhoId' => $whoId,\n 'WhatId' => $whatId,\n ];\n }\n\n private function saveCrmObject(string $objectType, Activity $activity, array $payload): void\n {\n /**\n * Tasks and events have different payload structures,\n * so we need to consider the type of the object we are sending to the CRM\n */\n $specificPayload = $objectType === Field::OBJECT_TASK\n ? $this->payloadBuilder->buildTaskPayload($activity)\n : $this->payloadBuilder->buildEventPayload($activity);\n\n $payload = array_merge($payload, $specificPayload);\n\n if ($activity->hasCrmProviderId()) {\n $this->logger->info('[Salesforce] Updating crm object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n try {\n $this->updateCrmActivity($objectType, $activity, $payload);\n } catch (HttpNotFoundException) {\n $this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $activity->setCrmProviderId(null);\n $activity->save();\n }\n\n return;\n }\n\n $this->logger->info('[Salesforce] Creating CRM object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $crmProviderId = $this->createRecord($objectType, $payload);\n\n $activity->setCrmProviderId($crmProviderId);\n $activity->save();\n }\n\n /**\n * @throws HttpNotFoundException\n */\n private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void\n {\n $sfActivity = $this->getRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n fields: ['Description', 'WhoId', 'WhatId']\n );\n\n if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {\n $this->logger->info('[Salesforce] Updating WhoId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n\n if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {\n $this->logger->info('[Salesforce] Updating WhatId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n } else {\n $payload['WhatId'] = null;\n }\n }\n\n $payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(\n $payload['Description'],\n $sfActivity['Description'] ?? null\n );\n\n $this->logger->info('[Salesforce] Updating CRM activity data', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n 'crmActivity' => $sfActivity,\n 'payload' => $payload,\n ]);\n\n $this->updateRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n data: $payload\n );\n }\n\n protected function getActivityDecorator(): DecorateActivity\n {\n if ($this->decorateActivity === null) {\n $this->decorateActivity = app(DecorateActivity::class);\n }\n\n return $this->decorateActivity;\n }\n\n private function resetLeadAssociation(Activity $activity): void\n {\n $activity->setStageId(null);\n $activity->setLeadId(null);\n $activity->save();\n }\n}","depth":4,"bounds":{"left":0.43882978,"top":0.5434956,"width":0.31848404,"height":0.4565044},"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits;\n\nuse Illuminate\\Events\\Dispatcher;\nuse Jiminny\\Events\\Activities\\Crm\\ActivityLeadConverted;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Feature\\FeatureEnum;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Services\\Crm\\Helpers\\CrmHelperRepository;\nuse Jiminny\\Services\\Crm\\Salesforce\\DecorateActivity;\nuse Jiminny\\Services\\Crm\\Salesforce\\PayloadBuilder;\nuse Psr\\Log\\LoggerInterface;\n\ntrait LogActivityTrait\n{\n public ?Configuration $config;\n public ?Profile $profile;\n\n protected PayloadBuilder $payloadBuilder;\n protected LoggerInterface $logger;\n protected Dispatcher $eventDispatcher;\n protected CrmHelperRepository $crmHelperRepository;\n protected ?DecorateActivity $decorateActivity = null;\n\n abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;\n abstract public function matchesCrmType(PlaybookCategory $category): bool;\n\n abstract public function syncLead(string $crmId): ?Lead;\n abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;\n abstract public function createRecord(string $objectType, array $data): string;\n abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;\n\n /**\n * Save an activity, update CRM prospect objects\n *\n * Create or update a task or event (depending on most applicable playbook)\n */\n public function saveActivity(Activity $activity): Activity\n {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n throw new InvalidArgumentException('Please configure a Playbook first.');\n }\n\n $this->logger->info('[Salesforce] Log activity', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n ]);\n\n $payload = [\n 'OwnerId' => $this->profile->getCrmProviderId(),\n 'Description' => $this->getActivityDecorator()->generateDescription($activity),\n ];\n\n $payload += $this->buildSubjectPayload($activity, $playbook);\n $payload += $this->buildProspectPayload($activity);\n\n $crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK\n ? Field::OBJECT_TASK\n : Field::OBJECT_EVENT;\n\n $this->logger->info('[Salesforce] Log activity. Payload Prepared', [\n 'activity_id' => $activity->getId(),\n 'object_type' => $playbook->getActivityType(),\n 'crm_object_type' => $crmObjectType,\n 'payload' => $payload,\n ]);\n\n $this->saveCrmObject($crmObjectType, $activity, $payload);\n\n return $activity;\n }\n\n private function buildSubjectPayload(Activity $activity, Playbook $playbook): array\n {\n if ($this->matchesCrmType($activity->getCategory())) {\n /**\n * If the activity playbook category name (i.e. activity type) matches a known activity type that exists\n * in the CRM, then we set the activity type in the payload.\n * Some activity types may be locally created. They shouldn't be sent to Salesforce.\n *\n * The resulting payload attribute will look like:\n * `Type` => 'Cold Call'\n */\n return [\n /** ActivityFieldID => ActivityType */\n $playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),\n 'Subject' => $this->getActivityDecorator()->generateTitle($activity),\n ];\n }\n\n /**\n * Building of the title seems very inconsistent\n * Subject here will be something like:\n * \"Local activity type: Activity Title\"\n */\n $subject = $activity->getCategory()->getName();\n if ($activity->getTitle() !== null) {\n $subject .= ': ' . $activity->getTitle();\n }\n\n return ['Subject' => $subject];\n }\n\n private function buildProspectPayload(Activity $activity): array\n {\n $payload = [];\n\n if ($activity->getAccountId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'account_id' => $activity->getAccountId(),\n 'opportunity_id' => $activity->getOpportunityId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $hasLinkFeature = $this->crmHelperRepository->hasFeature(\n $activity,\n FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS\n );\n\n if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())\n || (! $hasLinkFeature && $activity->getOpportunityId())\n ) {\n $payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();\n } else {\n $payload['WhatId'] = $activity->getAccount()->getCrmProviderId();\n }\n }\n\n if ($activity->getContactId()) {\n $this->logger->info('[Salesforce] Activity has account id', [\n 'activity_id' => $activity->getId(),\n 'contact_id' => $activity->getContactId(),\n ]);\n\n $payload['WhoId'] = $activity->getContact()->getCrmProviderId();\n } elseif ($activity->getLeadId()) {\n $this->logger->info('[Salesforce] Activity has lead id', [\n 'activity_id' => $activity->getId(),\n 'lead_id' => $activity->getLeadId(),\n ]);\n\n /**\n * An activity may have:\n * a) a contact | account | opportunity (or combinations)\n * b) only a lead\n * c) none of the above\n *\n * An activity should not have a lead, and another prospect object at the same time.\n *\n * This logical flow should not happen naturally, but as a fallback: if an activity has both\n * a Lead and an Account, the account's WhatId takes precedence in the CRM payload.\n * The lead association will be detached locally, but the account WhatId is preserved in Salesforce.\n */\n $payload += $this->handleActivityLead($activity);\n }\n\n return $payload;\n }\n\n private function handleActivityLead(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Activity sync lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Sync lead to pull fresh data. Leads change often,\n * they may get 'converted', and we must handle the new state accordingly\n */\n try {\n $activityLead = $this->syncLead(\n $activity->getLead()->getCrmProviderId()\n );\n } catch (HttpNotFoundException) {\n $this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not found, maybe it's remotely deleted\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n if ($activityLead === null) {\n $this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [\n 'activity_id' => $activity->getId(),\n ]);\n\n /**\n * Lead is not loaded, for some reason. It may be remotely found, but locally deleted.\n * Or an important Lead property may be missing, and it cannot be fully imported.\n */\n $this->resetLeadAssociation($activity);\n\n return [];\n }\n\n /**\n * The lead is not converted, directly use it as WhoId and move on.\n */\n if ($activityLead->getConvertedAt() === null) {\n return [\n 'WhoId' => $activity->getLead()->getCrmProviderId(),\n 'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.\n ];\n }\n\n /**\n * Task/Event payload properties for the CRM update\n */\n $whoId = null;\n $whatId = null;\n\n /**\n * Activity payload properties, that need to be updated.\n */\n $convertedOpportunityId = null;\n $convertedAccountId = null;\n $convertedContactId = null;\n $value = null;\n\n /**\n * If there is converted opportunity, it will update the activity stage.\n * If there isn't an opportunity, a converted account/contact cannot have a stage id,\n * so the activity shouldn't have a stage either.\n */\n $stageId = null;\n\n /**\n * The lead is definitely converted.\n * This means the lead may be associated with an opportunity, account, or contact.\n * The converted lead itself must be detached from the activity,\n * while the converted prospect objects must be associated instead,\n * since they now represent the state of the deal.\n */\n $activity->setLeadId(null);\n\n /**\n * CRM property \"WhatId\" can be either an Opportunity or an Account.\n * For us a converted Opportunity has higher priority than an Account.\n * An Opportunity carries more concrete data, including a reference to the Account record itself.\n */\n if ($activityLead->hasOpportunity()) {\n $convertedOpportunity = $activityLead->getOpportunity();\n\n $convertedOpportunityId = $convertedOpportunity->getId();\n $convertedAccountId = $convertedOpportunity->getAccountId();\n $stageId = $convertedOpportunity->getStageId();\n $value = $convertedOpportunity->getValue();\n\n $whatId = $convertedOpportunity->getCrmProviderId();\n }\n\n if ($activityLead->hasAccount()) {\n $convertedAccount = $activityLead->getAccount();\n\n $convertedAccountId ??= $convertedAccount->getId();\n\n $whatId ??= $convertedAccount->getCrmProviderId();\n }\n\n /**\n * WhoId can only be a Contact or a Lead.\n * Since we are detaching the Lead, it can only be a Contact for the current activity.\n * It does not conflict with any other object.\n */\n if ($activityLead->hasContact()) {\n $convertedContact = $activityLead->getContact();\n\n $convertedContactId = $convertedContact->getId();\n\n $whoId = $convertedContact->getCrmProviderId();\n }\n\n $activity->setOpportunityId($convertedOpportunityId);\n $activity->setAccountId($convertedAccountId);\n $activity->setContactId($convertedContactId);\n $activity->setStageId($stageId);\n $activity->setValue($value);\n\n $activity->save();\n\n $this->eventDispatcher->dispatch(\n new ActivityLeadConverted($activity, $activityLead)\n );\n\n $this->logger->info('[Salesforce] Lead is converted', [\n 'activity_id' => $activity->getId(),\n 'whoId' => $whoId,\n 'whatId' => $whatId,\n ]);\n\n return [\n 'WhoId' => $whoId,\n 'WhatId' => $whatId,\n ];\n }\n\n private function saveCrmObject(string $objectType, Activity $activity, array $payload): void\n {\n /**\n * Tasks and events have different payload structures,\n * so we need to consider the type of the object we are sending to the CRM\n */\n $specificPayload = $objectType === Field::OBJECT_TASK\n ? $this->payloadBuilder->buildTaskPayload($activity)\n : $this->payloadBuilder->buildEventPayload($activity);\n\n $payload = array_merge($payload, $specificPayload);\n\n if ($activity->hasCrmProviderId()) {\n $this->logger->info('[Salesforce] Updating crm object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n try {\n $this->updateCrmActivity($objectType, $activity, $payload);\n } catch (HttpNotFoundException) {\n $this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $activity->setCrmProviderId(null);\n $activity->save();\n }\n\n return;\n }\n\n $this->logger->info('[Salesforce] Creating CRM object', [\n 'activity_id' => $activity->getId(),\n 'crm_provider_id' => $activity->getCrmProviderId(),\n 'object_type' => $objectType,\n ]);\n\n $crmProviderId = $this->createRecord($objectType, $payload);\n\n $activity->setCrmProviderId($crmProviderId);\n $activity->save();\n }\n\n /**\n * @throws HttpNotFoundException\n */\n private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void\n {\n $sfActivity = $this->getRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n fields: ['Description', 'WhoId', 'WhatId']\n );\n\n if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {\n $this->logger->info('[Salesforce] Updating WhoId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n\n if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {\n $this->logger->info('[Salesforce] Updating WhatId', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n ]);\n } else {\n $payload['WhatId'] = null;\n }\n }\n\n $payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(\n $payload['Description'],\n $sfActivity['Description'] ?? null\n );\n\n $this->logger->info('[Salesforce] Updating CRM activity data', [\n 'objectType' => $objectType,\n 'activityId' => $activity->getUuid(),\n 'crmActivity' => $sfActivity,\n 'payload' => $payload,\n ]);\n\n $this->updateRecord(\n objectType: $objectType,\n objectId: $activity->getCrmProviderId(),\n data: $payload\n );\n }\n\n protected function getActivityDecorator(): DecorateActivity\n {\n if ($this->decorateActivity === null) {\n $this->decorateActivity = app(DecorateActivity::class);\n }\n\n return $this->decorateActivity;\n }\n\n private function resetLeadAssociation(Activity $activity): void\n {\n $activity->setStageId(null);\n $activity->setLeadId(null);\n $activity->save();\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
6476569718852315103
|
7759357447215520132
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
6
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Salesforce\ServiceTraits;
use Illuminate\Events\Dispatcher;
use Jiminny\Events\Activities\Crm\ActivityLeadConverted;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Activity;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Feature\FeatureEnum;
use Jiminny\Models\Lead;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Services\Crm\Helpers\CrmHelperRepository;
use Jiminny\Services\Crm\Salesforce\DecorateActivity;
use Jiminny\Services\Crm\Salesforce\PayloadBuilder;
use Psr\Log\LoggerInterface;
trait LogActivityTrait
{
public ?Configuration $config;
public ?Profile $profile;
protected PayloadBuilder $payloadBuilder;
protected LoggerInterface $logger;
protected Dispatcher $eventDispatcher;
protected CrmHelperRepository $crmHelperRepository;
protected ?DecorateActivity $decorateActivity = null;
abstract public function getPlaybookFromActivity(Activity $activity): ?Playbook;
abstract public function matchesCrmType(PlaybookCategory $category): bool;
abstract public function syncLead(string $crmId): ?Lead;
abstract public function getRecord(string $objectType, string $objectId, array $fields = []): array;
abstract public function createRecord(string $objectType, array $data): string;
abstract public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void;
/**
* Save an activity, update CRM prospect objects
*
* Create or update a task or event (depending on most applicable playbook)
*/
public function saveActivity(Activity $activity): Activity
{
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
throw new InvalidArgumentException('Please configure a Playbook first.');
}
$this->logger->info('[Salesforce] Log activity', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
]);
$payload = [
'OwnerId' => $this->profile->getCrmProviderId(),
'Description' => $this->getActivityDecorator()->generateDescription($activity),
];
$payload += $this->buildSubjectPayload($activity, $playbook);
$payload += $this->buildProspectPayload($activity);
$crmObjectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK
? Field::OBJECT_TASK
: Field::OBJECT_EVENT;
$this->logger->info('[Salesforce] Log activity. Payload Prepared', [
'activity_id' => $activity->getId(),
'object_type' => $playbook->getActivityType(),
'crm_object_type' => $crmObjectType,
'payload' => $payload,
]);
$this->saveCrmObject($crmObjectType, $activity, $payload);
return $activity;
}
private function buildSubjectPayload(Activity $activity, Playbook $playbook): array
{
if ($this->matchesCrmType($activity->getCategory())) {
/**
* If the activity playbook category name (i.e. activity type) matches a known activity type that exists
* in the CRM, then we set the activity type in the payload.
* Some activity types may be locally created. They shouldn't be sent to Salesforce.
*
* The resulting payload attribute will look like:
* `Type` => 'Cold Call'
*/
return [
/** ActivityFieldID => ActivityType */
$playbook->getActivityField()->getCrmProviderId() => $activity->getCategory()->getName(),
'Subject' => $this->getActivityDecorator()->generateTitle($activity),
];
}
/**
* Building of the title seems very inconsistent
* Subject here will be something like:
* "Local activity type: Activity Title"
*/
$subject = $activity->getCategory()->getName();
if ($activity->getTitle() !== null) {
$subject .= ': ' . $activity->getTitle();
}
return ['Subject' => $subject];
}
private function buildProspectPayload(Activity $activity): array
{
$payload = [];
if ($activity->getAccountId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'account_id' => $activity->getAccountId(),
'opportunity_id' => $activity->getOpportunityId(),
'contact_id' => $activity->getContactId(),
]);
$hasLinkFeature = $this->crmHelperRepository->hasFeature(
$activity,
FeatureEnum::LINK_ACTIVITY_TO_MULTIPLE_PROSPECTS
);
if (($hasLinkFeature && $activity->getOpportunityId() && ! $activity->getContactId())
|| (! $hasLinkFeature && $activity->getOpportunityId())
) {
$payload['WhatId'] = $activity->getOpportunity()->getCrmProviderId();
} else {
$payload['WhatId'] = $activity->getAccount()->getCrmProviderId();
}
}
if ($activity->getContactId()) {
$this->logger->info('[Salesforce] Activity has account id', [
'activity_id' => $activity->getId(),
'contact_id' => $activity->getContactId(),
]);
$payload['WhoId'] = $activity->getContact()->getCrmProviderId();
} elseif ($activity->getLeadId()) {
$this->logger->info('[Salesforce] Activity has lead id', [
'activity_id' => $activity->getId(),
'lead_id' => $activity->getLeadId(),
]);
/**
* An activity may have:
* a) a contact | account | opportunity (or combinations)
* b) only a lead
* c) none of the above
*
* An activity should not have a lead, and another prospect object at the same time.
*
* This logical flow should not happen naturally, but as a fallback: if an activity has both
* a Lead and an Account, the account's WhatId takes precedence in the CRM payload.
* The lead association will be detached locally, but the account WhatId is preserved in Salesforce.
*/
$payload += $this->handleActivityLead($activity);
}
return $payload;
}
private function handleActivityLead(Activity $activity): array
{
$this->logger->info('[Salesforce] Activity sync lead', [
'activity_id' => $activity->getId(),
]);
/**
* Sync lead to pull fresh data. Leads change often,
* they may get 'converted', and we must handle the new state accordingly
*/
try {
$activityLead = $this->syncLead(
$activity->getLead()->getCrmProviderId()
);
} catch (HttpNotFoundException) {
$this->logger->warning('[Salesforce] Activity lead is missing in Salesforce. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not found, maybe it's remotely deleted
*/
$this->resetLeadAssociation($activity);
return [];
}
if ($activityLead === null) {
$this->logger->warning('[Salesforce] Activity lead is missing in local DB. Resetting lead', [
'activity_id' => $activity->getId(),
]);
/**
* Lead is not loaded, for some reason. It may be remotely found, but locally deleted.
* Or an important Lead property may be missing, and it cannot be fully imported.
*/
$this->resetLeadAssociation($activity);
return [];
}
/**
* The lead is not converted, directly use it as WhoId and move on.
*/
if ($activityLead->getConvertedAt() === null) {
return [
'WhoId' => $activity->getLead()->getCrmProviderId(),
'WhatId' => null, // Clears WhatId on the remote record, unless an account WhatId was already set in the payload.
];
}
/**
* Task/Event payload properties for the CRM update
*/
$whoId = null;
$whatId = null;
/**
* Activity payload properties, that need to be updated.
*/
$convertedOpportunityId = null;
$convertedAccountId = null;
$convertedContactId = null;
$value = null;
/**
* If there is converted opportunity, it will update the activity stage.
* If there isn't an opportunity, a converted account/contact cannot have a stage id,
* so the activity shouldn't have a stage either.
*/
$stageId = null;
/**
* The lead is definitely converted.
* This means the lead may be associated with an opportunity, account, or contact.
* The converted lead itself must be detached from the activity,
* while the converted prospect objects must be associated instead,
* since they now represent the state of the deal.
*/
$activity->setLeadId(null);
/**
* CRM property "WhatId" can be either an Opportunity or an Account.
* For us a converted Opportunity has higher priority than an Account.
* An Opportunity carries more concrete data, including a reference to the Account record itself.
*/
if ($activityLead->hasOpportunity()) {
$convertedOpportunity = $activityLead->getOpportunity();
$convertedOpportunityId = $convertedOpportunity->getId();
$convertedAccountId = $convertedOpportunity->getAccountId();
$stageId = $convertedOpportunity->getStageId();
$value = $convertedOpportunity->getValue();
$whatId = $convertedOpportunity->getCrmProviderId();
}
if ($activityLead->hasAccount()) {
$convertedAccount = $activityLead->getAccount();
$convertedAccountId ??= $convertedAccount->getId();
$whatId ??= $convertedAccount->getCrmProviderId();
}
/**
* WhoId can only be a Contact or a Lead.
* Since we are detaching the Lead, it can only be a Contact for the current activity.
* It does not conflict with any other object.
*/
if ($activityLead->hasContact()) {
$convertedContact = $activityLead->getContact();
$convertedContactId = $convertedContact->getId();
$whoId = $convertedContact->getCrmProviderId();
}
$activity->setOpportunityId($convertedOpportunityId);
$activity->setAccountId($convertedAccountId);
$activity->setContactId($convertedContactId);
$activity->setStageId($stageId);
$activity->setValue($value);
$activity->save();
$this->eventDispatcher->dispatch(
new ActivityLeadConverted($activity, $activityLead)
);
$this->logger->info('[Salesforce] Lead is converted', [
'activity_id' => $activity->getId(),
'whoId' => $whoId,
'whatId' => $whatId,
]);
return [
'WhoId' => $whoId,
'WhatId' => $whatId,
];
}
private function saveCrmObject(string $objectType, Activity $activity, array $payload): void
{
/**
* Tasks and events have different payload structures,
* so we need to consider the type of the object we are sending to the CRM
*/
$specificPayload = $objectType === Field::OBJECT_TASK
? $this->payloadBuilder->buildTaskPayload($activity)
: $this->payloadBuilder->buildEventPayload($activity);
$payload = array_merge($payload, $specificPayload);
if ($activity->hasCrmProviderId()) {
$this->logger->info('[Salesforce] Updating crm object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
try {
$this->updateCrmActivity($objectType, $activity, $payload);
} catch (HttpNotFoundException) {
$this->logger->error('[Salesforce] Target crm object is missing in the crm. Resetting crm provider id', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$activity->setCrmProviderId(null);
$activity->save();
}
return;
}
$this->logger->info('[Salesforce] Creating CRM object', [
'activity_id' => $activity->getId(),
'crm_provider_id' => $activity->getCrmProviderId(),
'object_type' => $objectType,
]);
$crmProviderId = $this->createRecord($objectType, $payload);
$activity->setCrmProviderId($crmProviderId);
$activity->save();
}
/**
* @throws HttpNotFoundException
*/
private function updateCrmActivity(string $objectType, Activity $activity, array $payload): void
{
$sfActivity = $this->getRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
fields: ['Description', 'WhoId', 'WhatId']
);
if (! empty($payload['WhoId']) && $sfActivity['WhoId'] !== $payload['WhoId']) {
$this->logger->info('[Salesforce] Updating WhoId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
if (! empty($payload['WhatId']) && $sfActivity['WhatId'] !== $payload['WhatId']) {
$this->logger->info('[Salesforce] Updating WhatId', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
]);
} else {
$payload['WhatId'] = null;
}
}
$payload['Description'] = $this->getActivityDecorator()->mergeDescriptions(
$payload['Description'],
$sfActivity['Description'] ?? null
);
$this->logger->info('[Salesforce] Updating CRM activity data', [
'objectType' => $objectType,
'activityId' => $activity->getUuid(),
'crmActivity' => $sfActivity,
'payload' => $payload,
]);
$this->updateRecord(
objectType: $objectType,
objectId: $activity->getCrmProviderId(),
data: $payload
);
}
protected function getActivityDecorator(): DecorateActivity
{
if ($this->decorateActivity === null) {
$this->decorateActivity = app(DecorateActivity::class);
}
return $this->decorateActivity;
}
private function resetLeadAssociation(Activity $activity): void
{
$activity->setStageId(null);
$activity->setLeadId(null);
$activity->save();
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Sync Changes
Hide This Notification
Code changed:
Hide
8
1
3
4
Previous Highlighted Error...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45278
|
1623
|
21
|
2026-05-14T14:28:41.171795+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768921171_m1.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEdit ViewNavigateCodeLaravelRefactorRu PhpStormFileEdit ViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% (<478• Thu 14 May 17:28:40Fv faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :QProject v+.|•х:-© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.php© LocalSearch.php• LocalSearchlnterface.php• DeleteCrmEntityTrait.phpDeleteAccountJob.phpImportActivityTypes.phpT WriteCrmTrait.php© RemoteSearch.php© Salesforce/Service.php© LogActivityTrait.phpService.php XPlainTextDecorateActivity.php© Service.php© CrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18v D Listeners© ConvertLeadActivities.php© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.php© PurgeLookupCache.php› D Metadata© HubspotPaginationService.phpHandleHubspotRateLimit.php> Migrationv Pipedrive> D OpportunitySyncStrategy> ProspectSearchStrategy© ApiFields.php© Client.php© FieldDefinitions.php© PipedriveApiClient.php© PipedriveApiException.php© Service.php© TokenStorage.phpv D Salesforce> C Fields› OpportunityMatcher> C OpportunitySyncStrategy> D ProspectSearchStrategyv D ServiceTraitsT BatchSyncTrait.phpT FollowupActivityTrait.phpD LogActivityTrait.phpT RecordManipulationsTraiT SyncFieldsTrait.php© Client.php© DecorateActivity.php© DeleteObjectsTrait.php© FieldDefinitions.php@ PavinadRuilder nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=custom.logPlaybackController.phpSendReportJob.php=laravel.log© DecorateActivity.phpSF [jiminny@localhost]T ActivityPlaybookTrait.phpA HS_local [jiminny@localho:WE.env« console [QAI PROD) XClient.php4 console [PROD]A console (EU]D V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASE WHENidFROMsocial.1 on V.id = sa.:1..n<->1: on t.Lid = 1052 andIMaccounts wheiactivitiesW Windsurf Teams63:56UTF-8Co 4 spaces...
|
NULL
|
-6620716494202009342
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEdit ViewNavigateCodeLaravelRefactorRu PhpStormFileEdit ViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% (<478• Thu 14 May 17:28:40Fv faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :QProject v+.|•х:-© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.php© LocalSearch.php• LocalSearchlnterface.php• DeleteCrmEntityTrait.phpDeleteAccountJob.phpImportActivityTypes.phpT WriteCrmTrait.php© RemoteSearch.php© Salesforce/Service.php© LogActivityTrait.phpService.php XPlainTextDecorateActivity.php© Service.php© CrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18v D Listeners© ConvertLeadActivities.php© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.php© PurgeLookupCache.php› D Metadata© HubspotPaginationService.phpHandleHubspotRateLimit.php> Migrationv Pipedrive> D OpportunitySyncStrategy> ProspectSearchStrategy© ApiFields.php© Client.php© FieldDefinitions.php© PipedriveApiClient.php© PipedriveApiException.php© Service.php© TokenStorage.phpv D Salesforce> C Fields› OpportunityMatcher> C OpportunitySyncStrategy> D ProspectSearchStrategyv D ServiceTraitsT BatchSyncTrait.phpT FollowupActivityTrait.phpD LogActivityTrait.phpT RecordManipulationsTraiT SyncFieldsTrait.php© Client.php© DecorateActivity.php© DeleteObjectsTrait.php© FieldDefinitions.php@ PavinadRuilder nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=custom.logPlaybackController.phpSendReportJob.php=laravel.log© DecorateActivity.phpSF [jiminny@localhost]T ActivityPlaybookTrait.phpA HS_local [jiminny@localho:WE.env« console [QAI PROD) XClient.php4 console [PROD]A console (EU]D V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;1.id, CASE WHENidFROMsocial.1 on V.id = sa.:1..n<->1: on t.Lid = 1052 andIMaccounts wheiactivitiesW Windsurf Teams63:56UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45280
|
1624
|
14
|
2026-05-14T14:28:41.923061+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768921923_m2.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterday at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Yesterday at 13:21Yesterday at 13.20Yesterdav at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterday at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yesterday at 13:09Yesterday at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KBMPEG-4 movie6 KB12 Kb9 KBIMPEG-4 movieMPEG-4 movie7 KB8 KBMPEG-4 movie37 K:10 KBMPEG-4 movie7 KBMPEG-4 movie9 KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 K:13 KBMPEG-4 movie9 KB18 KB|MPEG-4 movie12 KBMPEG-4 movie10 KB16 KBMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie11 KEMPEG-4 movie11 KBMPEG-4 movie20 KB34 K:MPEG-4 movie10 KBMPEG-4 movie7 KB5KBMPEG-4 movie11 KPMPEG-4 movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:MPEG-4 movie88 KBMPEG-4 movie59 KB98 KBMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMPEG-4 movie7 KB12 KBMPEG-4 movie22 K:17 KBMPEG-4 movie19 KB32 K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-ywJo.ziPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfB Rovaix Famly Treo gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mау 1/.20.47Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-2597347445217722326
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterday at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Yesterday at 13:21Yesterday at 13.20Yesterdav at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterday at 13:15Yesterday at 13.10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yesterday at 13:09Yesterday at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KBMPEG-4 movie6 KB12 Kb9 KBIMPEG-4 movieMPEG-4 movie7 KB8 KBMPEG-4 movie37 K:10 KBMPEG-4 movie7 KBMPEG-4 movie9 KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 K:13 KBMPEG-4 movie9 KB18 KB|MPEG-4 movie12 KBMPEG-4 movie10 KB16 KBMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie11 KEMPEG-4 movie11 KBMPEG-4 movie20 KB34 K:MPEG-4 movie10 KBMPEG-4 movie7 KB5KBMPEG-4 movie11 KPMPEG-4 movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:MPEG-4 movie88 KBMPEG-4 movie59 KB98 KBMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMPEG-4 movie7 KB12 KBMPEG-4 movie22 K:17 KBMPEG-4 movie19 KB32 K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-ywJo.ziPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfB Rovaix Famly Treo gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mау 1/.20.47Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45276
|
NULL
|
NULL
|
NULL
|
|
45279
|
1623
|
22
|
2026-05-14T14:28:43.217302+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768923217_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
save
Inherited members (⌘R)
Anonymous Classes (⌘I) save
Inherited members (⌘R)
Anonymous Classes (⌘I)
Lambdas (⌘L)
Service, class
CALL_HEADER: string = 'Jiminny Summary', private
TASK_VERIFICATION_CACHE_TTL: int = 86400, private
opportunitySyncStrategyResolver: OpportunitySyncStrategyResolver, private
prospectPhotoPathService: ProspectPhotoPathService, parameter
__construct(client: Client, prospectPhotoPathService: ProspectPhotoPathService) ↑BaseService, public method
buildContactMobilePhone(countryCode: null|string, number: null|string): null|string, private method
buildContactPhone(countryCode: null|string, number: null|string): array|null, private method
buildTextMessagePayload(activity: Activity): Activity, private method
convertActivityAssociations(activity: Activity): array, private method
convertFieldType(fieldType: string): string, private method
convertObjectTypeToResource(objectType: string): Activities|Deals|Organizations|Persons, method
createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method
fetchCustomFieldData(activity: Activity, objectType: string): array, method
find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method
findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method
generateActivityDescription(activity: Activity): string, method
generateActivityTitle(activity: Activity): string, method
generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method
generateTranscription(activity: Activity): string, method
getBusinessProcesses(pipelineId: string): BusinessProcess|null, method
getCountryCode(contact, account): null|string, method
getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method
getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method
getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method
getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method
getDisplayName(): string ↑SettingsInterface, method
getFields(crmObject: string): array ↑BaseService, method
getFieldTypes(): array ↑BaseService, method
getOAuthAccount(user: User): SocialAccount|null ↑BaseService, method...
|
[{"role":"AXTextField","text [{"role":"AXTextField","text":"save","depth":1,"bounds":{"left":0.52152777,"top":0.32,"width":0.06458333,"height":0.031111112},"on_screen":true,"value":"save","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Inherited members (⌘R)","depth":1,"bounds":{"left":0.5277778,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Anonymous Classes (⌘I)","depth":1,"bounds":{"left":0.64444447,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Lambdas (⌘L)","depth":1,"bounds":{"left":0.76111114,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Service, class","depth":4,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"CALL_HEADER: string = 'Jiminny Summary', private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"TASK_VERIFICATION_CACHE_TTL: int = 86400, private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"opportunitySyncStrategyResolver: OpportunitySyncStrategyResolver, private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"prospectPhotoPathService: ProspectPhotoPathService, parameter","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"__construct(client: Client, prospectPhotoPathService: ProspectPhotoPathService) ↑BaseService, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"buildContactMobilePhone(countryCode: null|string, number: null|string): null|string, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"buildContactPhone(countryCode: null|string, number: null|string): array|null, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"buildTextMessagePayload(activity: Activity): Activity, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertActivityAssociations(activity: Activity): array, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertFieldType(fieldType: string): string, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertObjectTypeToResource(objectType: string): Activities|Deals|Organizations|Persons, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"fetchCustomFieldData(activity: Activity, objectType: string): array, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateActivityDescription(activity: Activity): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateActivityTitle(activity: Activity): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateTranscription(activity: Activity): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getBusinessProcesses(pipelineId: string): BusinessProcess|null, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getCountryCode(contact, account): null|string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method","depth":5,"bounds":{"left":0.55277777,"top":0.0,"width":0.36458334,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method","depth":5,"bounds":{"left":0.55277777,"top":0.0,"width":0.33819443,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method","depth":5,"bounds":{"left":0.55277777,"top":0.0,"width":0.33541667,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDisplayName(): string ↑SettingsInterface, method","depth":5,"bounds":{"left":0.55277777,"top":0.0,"width":0.20902778,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getFields(crmObject: string): array ↑BaseService, method","depth":5,"bounds":{"left":0.55277777,"top":0.02111111,"width":0.22916667,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getFieldTypes(): array ↑BaseService, method","depth":5,"bounds":{"left":0.55277777,"top":0.045555554,"width":0.17708333,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getOAuthAccount(user: User): SocialAccount|null ↑BaseService, method","depth":5,"bounds":{"left":0.55277777,"top":0.07,"width":0.29305556,"height":0.024444444},"on_screen":false,"role_description":"text"}]...
|
-8562237992472298740
|
3887466263308058721
|
visual_change
|
accessibility
|
NULL
|
save
Inherited members (⌘R)
Anonymous Classes (⌘I) save
Inherited members (⌘R)
Anonymous Classes (⌘I)
Lambdas (⌘L)
Service, class
CALL_HEADER: string = 'Jiminny Summary', private
TASK_VERIFICATION_CACHE_TTL: int = 86400, private
opportunitySyncStrategyResolver: OpportunitySyncStrategyResolver, private
prospectPhotoPathService: ProspectPhotoPathService, parameter
__construct(client: Client, prospectPhotoPathService: ProspectPhotoPathService) ↑BaseService, public method
buildContactMobilePhone(countryCode: null|string, number: null|string): null|string, private method
buildContactPhone(countryCode: null|string, number: null|string): array|null, private method
buildTextMessagePayload(activity: Activity): Activity, private method
convertActivityAssociations(activity: Activity): array, private method
convertFieldType(fieldType: string): string, private method
convertObjectTypeToResource(objectType: string): Activities|Deals|Organizations|Persons, method
createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method
fetchCustomFieldData(activity: Activity, objectType: string): array, method
find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method
findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method
generateActivityDescription(activity: Activity): string, method
generateActivityTitle(activity: Activity): string, method
generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method
generateTranscription(activity: Activity): string, method
getBusinessProcesses(pipelineId: string): BusinessProcess|null, method
getCountryCode(contact, account): null|string, method
getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method
getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method
getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method
getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method
getDisplayName(): string ↑SettingsInterface, method
getFields(crmObject: string): array ↑BaseService, method
getFieldTypes(): array ↑BaseService, method
getOAuthAccount(user: User): SocialAccount|null ↑BaseService, method...
|
45278
|
NULL
|
NULL
|
NULL
|
|
45281
|
1623
|
23
|
2026-05-14T14:28:46.228658+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768926228_m1.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEdit ViewNavigateCodeLaravelRefactorRu PhpStormFileEdit ViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.js* #12066 on JY-20725-handle-HS-search-rate-limit k vProject v© ReportController.php© AutomatedReportGenerated.phpabl100% (<47HandleHubspotRateLimitTestv8• Thu 14 May 17:28:45* :Q=custom.logTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© RemoteSearch.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpPlainTextDecorateActivity.php© Service.php© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php18v C Listeners© ConvertLeadActivities.phpE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.php© PurgeLookupCache.php› D Metadata© HubspotPaginationService.phpHandleHubspotRateLimit.php50classService extendsBaseService implements> C Migration1398*/v Pipedrive1399 @t ›public function matchByName(string $name, ?int $userId = null): ?array{...}> D OpportunitySyncStrategy> D ProspectSearchStrategy14791480/**© ApiFields.php1481* @inheritdoc© Client.php1482*/© FieldDefinitions.php1483 €public function saveActivity(Activity $activity): Activity© PipedriveApiClient.php© PipedriveApiException.php1484© Service.php1485switch (Sactivity->type) {© TokenStorage.php1486case Activity:: TYPE_CONFERENCE:v D Salesforce1487case Activity:: TYPE_SOFTPHONE:1488case Activity: : TYPE_SOFTPHONE_INBOUND:> C Fields> OpportunityMatcher1489Sactivity = $this->buildCallPayload(Sactivity);1490> C OpportunitySyncStrategy> D ProspectSearchStrategy1491break;v D ServiceTraits1492case Activity: : TYPE_SMS_INBOUND:D BatchSyncTrait.php1493case Activity::TYPE_SMS_OUTBOUND:T FollowupActivityTrait.php1494Sactivity = Sthis->buildTextMessagePayload(Sactivity);D LogActivityTrait.php14951496break;T RecordManipulationsTrai1497T SyncFieldsTrait.php1498© Client.php1499return $activity:© DecorateActivity.php1500DeleteObjectsTrait.php1501© FieldDefinitions.php4 usages© PavinadRuilder nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.log© DecorateActivity.phpSF [jiminny@localhost]A HS_local [jiminny@localho:W= .env.staging4 console [QAI PROD] XClient.php4 console [PROD]A console (EU]A6DGo jiminny08A1 43M4AY211m migrations oi212—213— 214215— 216m teams wherem crm_layouts !M crm_layout_eilIM crm_fields Wi217— 218219=220m features;m team_feature:m opportunitie:E221222m teams;—2232241.id, CASEWHEN225226227- 228= 229— 230,id FROM social,1 on V.id = sa.:1..n<->1: on t.L_id = 1052 and231232- 233 /IMaccounts wheiactivities234W Windsurf Teams1483:21UTF-8P. 4 spaces...
|
NULL
|
-8215475901560601790
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEdit ViewNavigateCodeLaravelRefactorRu PhpStormFileEdit ViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.js* #12066 on JY-20725-handle-HS-search-rate-limit k vProject v© ReportController.php© AutomatedReportGenerated.phpabl100% (<47HandleHubspotRateLimitTestv8• Thu 14 May 17:28:45* :Q=custom.logTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© RemoteSearch.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpPlainTextDecorateActivity.php© Service.php© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php18v C Listeners© ConvertLeadActivities.phpE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.php© PurgeLookupCache.php› D Metadata© HubspotPaginationService.phpHandleHubspotRateLimit.php50classService extendsBaseService implements> C Migration1398*/v Pipedrive1399 @t ›public function matchByName(string $name, ?int $userId = null): ?array{...}> D OpportunitySyncStrategy> D ProspectSearchStrategy14791480/**© ApiFields.php1481* @inheritdoc© Client.php1482*/© FieldDefinitions.php1483 €public function saveActivity(Activity $activity): Activity© PipedriveApiClient.php© PipedriveApiException.php1484© Service.php1485switch (Sactivity->type) {© TokenStorage.php1486case Activity:: TYPE_CONFERENCE:v D Salesforce1487case Activity:: TYPE_SOFTPHONE:1488case Activity: : TYPE_SOFTPHONE_INBOUND:> C Fields> OpportunityMatcher1489Sactivity = $this->buildCallPayload(Sactivity);1490> C OpportunitySyncStrategy> D ProspectSearchStrategy1491break;v D ServiceTraits1492case Activity: : TYPE_SMS_INBOUND:D BatchSyncTrait.php1493case Activity::TYPE_SMS_OUTBOUND:T FollowupActivityTrait.php1494Sactivity = Sthis->buildTextMessagePayload(Sactivity);D LogActivityTrait.php14951496break;T RecordManipulationsTrai1497T SyncFieldsTrait.php1498© Client.php1499return $activity:© DecorateActivity.php1500DeleteObjectsTrait.php1501© FieldDefinitions.php4 usages© PavinadRuilder nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.log© DecorateActivity.phpSF [jiminny@localhost]A HS_local [jiminny@localho:W= .env.staging4 console [QAI PROD] XClient.php4 console [PROD]A console (EU]A6DGo jiminny08A1 43M4AY211m migrations oi212—213— 214215— 216m teams wherem crm_layouts !M crm_layout_eilIM crm_fields Wi217— 218219=220m features;m team_feature:m opportunitie:E221222m teams;—2232241.id, CASEWHEN225226227- 228= 229— 230,id FROM social,1 on V.id = sa.:1..n<->1: on t.L_id = 1052 and231232- 233 /IMaccounts wheiactivities234W Windsurf Teams1483:21UTF-8P. 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45282
|
1624
|
15
|
2026-05-14T14:28:46.637506+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768926637_m2.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15resterday at 13-10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mау 1/.20.40Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-4350145192211111468
|
NULL
|
click
|
ocr
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterday at 13.34Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:32resterday al i5.sYesterdav at 13:31Yesterday at 13:30Yesterday at 13.29Yesterdav at 13:29resterday at 15.2oYesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterdav at 13:25Yesterday at 13.24Yesterdav at 13:24Yesterday at 13:23Yesterday at 13:21Voctorday at 12:21Yesterday at 13.20Yesterdav at 13:19Yesterdav at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13:17Yesterday at 13.16Yecterdav at 12:16Yesterdav at 13:15resterday at 13-10Yesterdav at 13:14Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterday at 13.11Yesterdav at 13:11Yesterday at 13:10Yesterday at 13:09Yoctorday at 12:00Yesterdav at 13:08Yesterday at 13.08Yecterdav at 12:07Yesterday at 13:07Yesterdav at 13:0617K:MPEG-4 movie29 KB6 KB12 Kb9 KBI7 KB8 KB37 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPEG-4 movie10 KB7 KBMDEG-A movieMPEG-4 movie9 KBI8 KB72 KB14 K:MPEG-4 movieMPEG-4 movie13 KBMDECA mavile9 KB18 KB|MPEG-4 movie12 KBI10 KB16 KBMPEG-1 movidMPEG-4 movie6KEMPEG-4 movie6 KB MPEG-4 movie12 KB23 K:MPEG-4 movie8 KB6 KBMDSG.A movicMPEG-4 movie11 KE11 KBMPEG-4 movieMPEG-4 movie20 KB34 K:MPEG-4 movie10kр7 KB5KBMDEG.A movidMPEG-4 movie11 KPMDEG-A movie26 KB MPEG-4 movie111 KBMPEG-4 movie102 K:88 KB59 KB98 KBMPEG-4 movieMDEC.A moviaMPEG-4 movie07 KPMDEG-A movie66 KBMPEG-4 movie44 KBMPEG-4 movie03 K:IMPEG-A movid78 KB MPEG-4 movie50 KB58 KB27 KPMPEG-4 movieMDEG.A movio7 KB12 KBMPEG-4 movie22 K:17 KBMDEC A movid19 KB32 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esviconfig.vmlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•Alfredv P1 mazanoko imaaoc. VWI6ана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.54 GB availabld• Inu 14 Mау 1/.20.40Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45283
|
1623
|
24
|
2026-05-14T14:29:01.717170+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768941717_m1.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8043719072324535154
|
-8628527368849355612
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
PhpStormFileEditViewNavig Project: faVsco.js, menu
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.js* #12066 on JY-20725-handle-HS-search-rate-limit k vProject v© ReportController.php© AutomatedReportGenerated.phpablHandleHubspotRateLimitTest100% C8• Thu 14 May 17:29:01* :QTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.log© DecorateActivity.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© LocalSearch.php• LocalSearchlnterface.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© RemoteSearch.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpPlainTextDecorateActivity.php© Service.php18v C Listeners© ConvertLeadActivities.php© ActivityPlaybookTrait.phpE.envCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.stagingDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.php© PurgeLookupCache.php› D Metadata50> C MigrationA5 A 119 X3 X9 ^1511v Pipedrive1515© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass Service extends BaseServiceimplementsprivate function buildCallPayload(Activity $activity): Activitythrow new Exception( message: 'No mapped CRM type in Pipedrive for "*• Sactivity->category->name> D OpportunitySyncStrategy> D ProspectSearchStrategy15161517© ApiFields.php1518© Client.php1519© FieldDefinitions.php© PipedriveApiClient.php15201521© PipedriveApiException.php© Service.php15221523© TokenStorage.phpv D Salesforce15241525> C Fields> OpportunityMatcher15261527> C OpportunitySyncStrategy> D ProspectSearchStrategy1528$data = ['done' => 1,'user_id' => $this->profile->crm_provider_id,'due_time' => $activity->scheduled_start_time->format( format: 'H:i'),'due_date' => Sactivity->scheduled_start_time->toDateString(),'duration' => gmdate( format: 'H:i', $activity->duration),'type' => $type->value,'subject' => Sthis->generateActivityTitle(Sactivity),'note' => $this->generateActiv] + $this->fetchCustomFieldData($a+ $this->convertActivityAssociat1529C ServiceTraits© Serviceprivate function generateActivityTitle(Activity $activity): string1530return Sthis->upsertActivity(SactiT BatchSyncTrait.php1531T FollowupActivityTrait.phpParameters: \ActivitySactivityD LogActivityTrait.php15321 usageSource:T RecordManipulationsTrai1533private function buildTextMessagePaylo.../app/Services/Crm/Pipedrive/Service.phpT SyncFieldsTrait.php1552© Client.php2 usages© DecorateActivity.phpC DeleteObjectsTrait.php15531576private function upsertActivity(Activity Sactivity, array $data): Activity{...© FieldDefinitions.php1 usage© PavinadRuilder nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D211Go jiminny0841A3 X4 A Vm migrations oi212=213=214215=216=m teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wi217: 218219220m features;m team_feature:m opportunitie:III221.222m teams;— 223|= 224|1.id, CASEWHEN-225-226=227—- 228229=230idFROMsocial,1 on u.id= sa.:1..n<->1: on t.Lid = 1052 and=231— 232=233 vIMaccounts wheiactivities=2341511:22UTF-8Co 4 spaces...
|
45281
|
NULL
|
NULL
|
NULL
|
|
45285
|
1624
|
16
|
2026-05-14T14:29:01.720690+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768941720_m2.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8043719072324535154
|
-8628527368849355612
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
Jiminny... ~ActivityFiles Project: faVsco.js, menu
Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterdav at 13.35Yesterday at 13:34Yesterday at 13.33Yesterdav at 13:33Yesterday at 13:32Yesterday at 13:32Yesterday at 13:31Yesterday at 13.30Yesterdav at 13:29Yesterday at 13:29resterday at 15.2oYesterdav at 13:28Yesterday at 13:27Yesterday at 13:26Yesterdav at 13:26resterday at 13-40Yesterdav at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.20Yesterdav at 13:20Yesterdav at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13:18Yesterday at 13.17Yecterdav at 12:16Yesterdav at 13:16Yesterday at 13.10Yesterdav at 13:15Yesterday at 13:14Yesterday at 13:13Yecterdav at 12:12Yesterdav at 13:12Yesterday at 13.12Yesterdav at 13:11Yesterday at 13:11Yesterday at 13:10Yoctorday at 12:00Yesterdav at 13:09Yesterday at 13.08Yocterdav at 12:08Yesterdav at 13:07Yesterdav at 13:0616 K:MPEG-4 movie17 KB29 KBMDEG-A movieMPEG-4 movieMPEG-4 movie12 KE9 KBMPE0"4 movie8 K:37 KB10 KBIKBnMDSG-A movieMP2G-4 movie8 KBI9 KB8 KB72 K:MPEG-4 movieMPEG-4 movie14 KB13 KBMoECA movieMPEG-4 movie18 KBI12 KB10 KBMPEG-1 movidMPEG-4 movie16 KEMPEG-4 movie6 KB MPEG-4 movie6 KB12 KB|MPEG-4 movie23 KBMDSG.A movicMPEG-4 movie6KE11 KBMPEG-4 movieMPEG-4 movie11 KBMPEG-4 movie20 K:MPEG-4 movie2AKR10 KB7 KBMDEGA movidMPEG-4 movie5KPMDEG-A movie11 KBMPEG-4 movie26 KBMPEG-4 movie111 K:102 KB88 KB59 KBMPEG-4 movieMDEC.A moviaMPEG-4 movieO9 KR97 KB66 KBMDEG-A movieMPEG-4 movie44K:MPSG-A movid93 KBMPEG-4 movie78 KB50 KB59 KPMPEG-4 movieMDEG.A movio27 KBMPEG-4 movie12 K:32 KBMDEC A movid17 KB19K8MPEG-4 movie• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfP Kdf-a,k Ffmiv Tree.sebitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.53 GB availabld• Inu 14 May 1/.29:0.Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45282
|
NULL
|
NULL
|
NULL
|
|
45284
|
1623
|
25
|
2026-05-14T14:29:03.632493+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768943632_m1.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3
9
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Pipedrive;
use Carbon\Carbon;
use Devio\Pipedrive\Exceptions\ItemNotFoundException;
use Devio\Pipedrive\Exceptions\PipedriveException;
use Exception;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\PipedriveInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Events\Users\SocialAccountDisconnected;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\SocialAccountTokenInvalidException;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Log;
use UnexpectedValueException;
class Service extends BaseService implements
PipedriveInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string CALL_HEADER = 'Jiminny Summary';
/**
* @var ClientInterface|Client
*/
protected $client;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)
{
parent::__construct();
$this->client = $client;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Pipedrive';
}
/**
* @inheritdoc
*/
public function setUser(User $user): void
{
try {
parent::setUser($user);
} catch (InvalidArgumentException $exception) {
// In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.
if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&
$exception->getMessage() === 'Required option not passed: "access_token"') {
// Something terrible happened to their token, they need to reconnect.
$this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);
event(new SocialAccountDisconnected($this->client->oauthAccount));
}
throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');
}
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
switch ($fieldType) {
case Field::TYPE_DATE:
$value = $internal ? Carbon::parse($fieldValue) : $fieldValue;
break;
default:
$value = $fieldValue;
}
return $value;
}
/**
* Gets the valid fields for a given Object via the property APIs.
*
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
switch ($crmObject) {
case 'task':
$properties = $this->client->getInstance()->activityFields();
break;
case 'account':
$properties = $this->client->getInstance()->organizationFields();
break;
case 'contact':
$properties = $this->client->getInstance()->personFields();
break;
case 'opportunity':
$properties = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException();
}
$fields = [];
try {
$response = $properties->all();
if ($response->isSuccess() === false) {
throw new Exception($response->getContent(), $response->getStatusCode());
}
foreach ($response->getData() as $property) {
$fields[] = ['label' => $property->name, 'name' => $property->key];
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
return;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
$field->description = null;
$field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($crmField->field_type);
$field->is_selectable = $crmField->active_flag;
$field->save();
}
}
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'enum':
case 'stage':
case 'status':
return Field::TYPE_PICKLIST;
case 'varchar':
return Field::TYPE_TEXT;
case 'int':
case 'double':
return Field::TYPE_NUMBER;
case 'text':
return Field::TYPE_TEXTAREA;
case 'monetary':
return Field::TYPE_CURRENCY;
case Field::TYPE_DATE:
case Field::TYPE_TIME:
case Field::TYPE_PHONE:
return $fieldType;
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException('Invalid field type "' . $field->object_type . '" for field ' . $field->id . '.');
}
if ($field->crm_provider_id == 'stage_id') {
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();
foreach ($dealStages as $i => $dealStage) {
$values = [
'value' => $dealStage->id,
'label' => $dealStage->name,
'sequence' => $i,
];
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $dealStage->id,
], $values);
}
}
return $fieldValues;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
// Import all active values.
if (property_exists($crmField, 'options')) {
foreach ($crmField->options as $i => $option) {
$values[] = [
'value' => $option->id,
'label' => $option->label,
'sequence' => $i,
];
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
return $fieldValues;
}
/**
* @inheritdoc
*
* @throws SocialAccountTokenInvalidException
* @throws PipedriveException
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// We create a business process to contain the pipeline, and later store all stages against it.
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$businessProcess = $this->importPipelineData($pipeline);
$stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);
if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {
$missingStage = $stage;
}
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
// Pipedrive doesn't use leads.
return 0;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
// Pipedrive doesn't use leads.
return null;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdAccounts = $this->client->getInstance()->organizations()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdAccounts->getData() === null) {
return 0;
}
foreach ($pdAccounts->getData() as $pdAccount) {
// Only sync if previously imported.
if ($this->hasAccount($pdAccount->id)) {
$this->importAccount($pdAccount);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
try {
$hsAccount = $this->client->getInstance()->organizations()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);
}
return $this->importAccount($hsAccount->getData());
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = $crmData->country_code;
if ($countryCode === null && $crmData->address_country) {
$countryCode = $this->convertCountryNameToCode($crmData->address_country);
}
$name = $crmData->name;
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
/**
* Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.
* These are real samples from API results:
* { ... owner_id: 23696001, ...}
* OR
* {
* ...
* owner_id: {
* active_flag: false,
* id: 12972717,
* name: 'name here',
* value: 12972717
* }
* }
*/
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Account::class,
fileName: (string) $crmData->id,
avatarText: $name,
),
'country_code' => $countryCode,
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Account */
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {
$this->importOpportunity($pdOpportunity);
$syncCount++;
}
}
$this->logger->info('[Pipedrive] Sync Opportunities completed', [
'team' => $this->team->getId(),
'syncCount' => $syncCount,
]);
} catch (Exception $exception) {
$this->logger->info('[Pipedrive] Failed to sync Opportunities ', [
'team' => $this->team->getId(),
'params' => $parameters,
'strategy' => $strategy,
'reason' => $exception->getMessage(),
'syncedBeforeFailure' => $syncCount,
]);
}
if ($syncCount > 1000) {
$this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [
'team' => $this->team->getId(),
'total' => $syncCount,
]);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = ['crm_id' => $crmId];
try {
$generator = $strategy->fetchOpportunities($parameters);
$pdOpportunity = $generator->current();
} catch (ItemNotFoundException | PipedriveException $e) {
$this->logger->info('[Pipedrive] Failed to sync opportunity', [
'crm_id' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
return $this->importOpportunity($pdOpportunity);
}
/**
* @inheritdoc
*/
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData->deleted) {
return null;
}
if ($crmData->org_id) {
$orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();
if ($account === null) {
$account = $this->syncAccount($orgId);
if ($account === null) {
// For some bizarre reason, the org_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);
return null;
}
}
} elseif ($crmData->person_id) {
// Try to get the organization from the person.
$personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;
$contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();
if ($contact === null || $contact->account_id === null) {
$contact = $this->syncContact($personId);
if ($contact === null) {
// For some bizarre reason, the person_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);
return null;
}
if ($contact->account_id === null) {
$this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());
return null;
}
}
$account = $contact->account;
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $crmData->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$closeDate = null;
if ($crmData->expected_close_date) {
$closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');
}
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
$data = [
'team_id' => $this->team?->getId(),
'account_id' => $account?->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->title, 0, 128),
'value' => $crmData->value,
'currency_code' => CurrencyFormatter::formatCode($crmData->currency),
'close_date' => $closeDate,
'is_closed' => $crmData->close_time !== null,
'is_won' => $crmData->won_time !== null,
'stage_id' => $stage?->getId(),
'record_type_id' => $recordType?->getId(),
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Opportunity $opportunity */
$opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
// import external fields into crm_field_data if present
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdContacts = $this->client->getInstance()->persons()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdContacts->getData() === null) {
return 0;
}
foreach ($pdContacts->getData() as $pdContact) {
// Only sync if previously imported.
if ($this->hasContact($pdContact->id)) {
$this->importContact($pdContact);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
try {
$pdContact = $this->client->getInstance()->persons()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);
}
return $this->importContact($pdContact->getData());
}
private function importContact($crmData): Contact
{
$photoPath = null;
$account = null;
if ($crmData->org_id) {
/**
* Pipedrive API is inconsistent, it may return a string variable, or an object
*/
$crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config
->accounts()
->where('crm_provider_id', $crmProviderId)
->first();
if ($account === null) {
$account = $this->syncAccount($crmProviderId);
$photoPath = $this->teamService->generateAvatar(
$crmData->id,
$crmData->name,
);
} else {
$photoPath = $account->photo_path;
}
}
if ($photoPath === null) {
$photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Contact::class,
fileName: (string) $crmData->id,
avatarText: $crmData->name,
);
}
$ownerId = $profile = null;
if ($crmData->owner_id) {
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
}
$parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);
$mobileNumber = null;
if (isset($crmData->phone[1])) {
$mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);
}
$email = null;
if (isset($crmData->email[0]->value)) {
$email = mb_strimwidth($crmData->email[0]->value, 0, 191);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->name ?? '', 0, 100),
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobileNumber ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData->job_title ?? null,
'photo_path' => $photoPath,
'remotely_created_at' => Carbon::parse($crmData->add_time),
];
/** @var Contact */
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
// Not applicable.
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?\Jiminny\Models\Crm\Profile
{
// Not needed yet.
return null;
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);
/*
// If they have changed, raise a notification to the owner.
$team->owner->notify(
new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)
);
*/
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (Exception $exception) {
Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {
$data = [];
$params = [
'term' => $name,
'limit' => $count,
'start' => $offset,
'item_types' => 'person,organization',
];
$objects = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$objects = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
if (empty($objects['items'])) {
return [];
}
// Build mapped list.
foreach ($objects['items'] as $object) {
$object = $object['item'];
// We only support these object types today.
if (\in_array($object['type'], ['person', 'organization']) === false) {
continue;
}
$objectType = $object['type'] === 'person' ? 'contact' : 'account';
$record = [
'crmId' => $object['id'],
'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),
'name' => $object['name'],
'industry' => null,
'title' => null,
'prospectType' => $objectType,
'phoneNumbers' => [],
];
if (isset($object['organization']['name'])) {
$record['organization'] = $object['organization']['name'];
}
if (isset($object['phones'][0])) {
$parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);
// Add phone number to record.
if (empty($parsedNumber['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $parsedNumber['phone'],
'nationalFormat' => phone_national(null, $parsedNumber['phone']),
'type' => 'phone',
];
}
}
$data[] = $record;
}
return $data;
});
return $data;
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'only_primary_association' => 1,
'status' => 'open',
'sort' => 'update_time DESC',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = 'add_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = 'add_time ASC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
$params['status'] = 'all_not_deleted';
}
$pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
if ($pdOpportunities === null) {
return [];
}
foreach ($pdOpportunities as $pdOpportunity) {
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$record = [
'crmId' => $pdOpportunity->id,
'name' => $pdOpportunity->title,
'value' => $pdOpportunity->formatted_value,
'won' => $pdOpportunity->won_time !== null,
'closed' => $pdOpportunity->status !== 'open',
'stage' => [
'id' => $stage?->id_string ?? '',
'name' => $stage?->name ?? '',
],
'recordType' => [
'id' => $recordType?->id_string ?? '',
'name' => $recordType?->name ?? '',
],
];
if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
$pdActivities = null;
$filters = ['done' => 0];
switch ($objectType) {
case 'contact':
$pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();
break;
case 'account':
// Prioritize looking up activities on the deal (which should be linked on the account anyway).
if ($opportunityId) {
$pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();
}
// If no deal activity, fall back to the organization.
if ($pdActivities === null) {
$pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();
}
break;
}
if ($pdActivities === null) {
return [];
}
foreach ($pdActivities as $pdActivity) {
// Only import active, scheduled tasks in the future.
if ($pdActivity->active_flag) {
$due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');
$data[] = [
'crmId' => $pdActivity->id,
'subject' => $pdActivity->subject,
'due' => Carbon::parse($due)->toIso8601String(),
'type' => $pdActivity->type,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contact = null;
$account = null;
$params = [
'term' => $email,
'item_types' => 'person',
'fields' => 'email',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
$this->logger->info('[Pipedrive] Email match failed', [
'email' => $email,
'reason' => $exception->getMessage(),
]);
return null;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if (
! $contact instanceof Contact
&& ! $account instanceof Account
) {
return null;
}
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (count($pdOpportunities) > 0) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
// Check if the user is internal.
$teamMember = $this->team->users()->where('phone', $phone)->exists();
// Skip the attendee if internal.
if ($teamMember !== false) {
return null;
}
$params = [
'term' => $phone,
'item_types' => 'person,organization',
'fields' => 'phone',
];
$searchResult = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$searchResult = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Phone match failed', [
'phone' => $phone,
'reason' => $e->getMessage(),
]);
return null;
}
if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {
return null;
}
$contact = $this->syncContact($searchResult['items'][0]['item']['id']);
$account = $contact->account;
$countryCode = $this->getCountryCode($contact, $account);
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function getCountryCode($contact, $account): ?string
{
if ($contact && $contact->country_code) {
return $contact->country_code;
} elseif ($account && $account->country_code) {
return $account->country_code;
}
return null;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {
$contact = null;
$account = null;
$params = [
'term' => $name,
'item_types' => 'person',
'fields' => 'name',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Name match failed', [
'name' => $name,
'reason' => $e->getMessage(),
]);
return false;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if ($contact || $account) {
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
return false;
});
return is_array($result) ? $result : null;
}
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->type) {
case Activity::TYPE_CONFERENCE:
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildCallPayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"5","depth":4,"bounds":{"left":0.73194444,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"119","depth":4,"bounds":{"left":0.75277776,"top":0.3122222,"width":0.023611112,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.78055555,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.80138886,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Pipedrive;\n\nuse Carbon\\Carbon;\nuse Devio\\Pipedrive\\Exceptions\\ItemNotFoundException;\nuse Devio\\Pipedrive\\Exceptions\\PipedriveException;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\PipedriveInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Events\\Users\\SocialAccountDisconnected;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\SocialAccountTokenInvalidException;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Log;\nuse UnexpectedValueException;\n\nclass Service extends BaseService implements\n PipedriveInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string CALL_HEADER = 'Jiminny Summary';\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)\n {\n parent::__construct();\n\n $this->client = $client;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Pipedrive';\n }\n\n /**\n * @inheritdoc\n */\n public function setUser(User $user): void\n {\n try {\n parent::setUser($user);\n } catch (InvalidArgumentException $exception) {\n // In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.\n if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&\n $exception->getMessage() === 'Required option not passed: \"access_token\"') {\n // Something terrible happened to their token, they need to reconnect.\n $this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);\n\n event(new SocialAccountDisconnected($this->client->oauthAccount));\n }\n\n throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');\n }\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n switch ($fieldType) {\n case Field::TYPE_DATE:\n $value = $internal ? Carbon::parse($fieldValue) : $fieldValue;\n\n break;\n\n default:\n $value = $fieldValue;\n }\n\n return $value;\n }\n\n /**\n * Gets the valid fields for a given Object via the property APIs.\n *\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n switch ($crmObject) {\n case 'task':\n $properties = $this->client->getInstance()->activityFields();\n\n break;\n\n case 'account':\n $properties = $this->client->getInstance()->organizationFields();\n\n break;\n\n case 'contact':\n $properties = $this->client->getInstance()->personFields();\n\n break;\n\n case 'opportunity':\n $properties = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException();\n }\n\n $fields = [];\n\n try {\n $response = $properties->all();\n\n if ($response->isSuccess() === false) {\n throw new Exception($response->getContent(), $response->getStatusCode());\n }\n\n foreach ($response->getData() as $property) {\n $fields[] = ['label' => $property->name, 'name' => $property->key];\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n return;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n $field->description = null;\n $field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($crmField->field_type);\n $field->is_selectable = $crmField->active_flag;\n $field->save();\n }\n }\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'enum':\n case 'stage':\n case 'status':\n return Field::TYPE_PICKLIST;\n\n case 'varchar':\n return Field::TYPE_TEXT;\n\n case 'int':\n case 'double':\n return Field::TYPE_NUMBER;\n\n case 'text':\n return Field::TYPE_TEXTAREA;\n\n case 'monetary':\n return Field::TYPE_CURRENCY;\n\n case Field::TYPE_DATE:\n case Field::TYPE_TIME:\n case Field::TYPE_PHONE:\n return $fieldType;\n\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException('Invalid field type \"' . $field->object_type . '\" for field ' . $field->id . '.');\n }\n\n if ($field->crm_provider_id == 'stage_id') {\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n foreach ($pipelines as $pipeline) {\n $dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();\n foreach ($dealStages as $i => $dealStage) {\n $values = [\n 'value' => $dealStage->id,\n 'label' => $dealStage->name,\n 'sequence' => $i,\n ];\n\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $dealStage->id,\n ], $values);\n }\n }\n\n return $fieldValues;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n // Import all active values.\n if (property_exists($crmField, 'options')) {\n foreach ($crmField->options as $i => $option) {\n $values[] = [\n 'value' => $option->id,\n 'label' => $option->label,\n 'sequence' => $i,\n ];\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n *\n * @throws SocialAccountTokenInvalidException\n * @throws PipedriveException\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // We create a business process to contain the pipeline, and later store all stages against it.\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n\n foreach ($pipelines as $pipeline) {\n $businessProcess = $this->importPipelineData($pipeline);\n\n $stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);\n if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {\n $missingStage = $stage;\n }\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n // Pipedrive doesn't use leads.\n return 0;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n // Pipedrive doesn't use leads.\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdAccounts = $this->client->getInstance()->organizations()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdAccounts->getData() === null) {\n return 0;\n }\n\n foreach ($pdAccounts->getData() as $pdAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($pdAccount->id)) {\n $this->importAccount($pdAccount);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $hsAccount = $this->client->getInstance()->organizations()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importAccount($hsAccount->getData());\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData->country_code;\n if ($countryCode === null && $crmData->address_country) {\n $countryCode = $this->convertCountryNameToCode($crmData->address_country);\n }\n\n $name = $crmData->name;\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n /**\n * Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.\n * These are real samples from API results:\n * { ... owner_id: 23696001, ...}\n * OR\n * {\n * ...\n * owner_id: {\n * active_flag: false,\n * id: 12972717,\n * name: 'name here',\n * value: 12972717\n * }\n * }\n */\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Account::class,\n fileName: (string) $crmData->id,\n avatarText: $name,\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Account */\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {\n $this->importOpportunity($pdOpportunity);\n $syncCount++;\n }\n }\n\n $this->logger->info('[Pipedrive] Sync Opportunities completed', [\n 'team' => $this->team->getId(),\n 'syncCount' => $syncCount,\n ]);\n } catch (Exception $exception) {\n $this->logger->info('[Pipedrive] Failed to sync Opportunities ', [\n 'team' => $this->team->getId(),\n 'params' => $parameters,\n 'strategy' => $strategy,\n 'reason' => $exception->getMessage(),\n 'syncedBeforeFailure' => $syncCount,\n ]);\n }\n\n if ($syncCount > 1000) {\n $this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [\n 'team' => $this->team->getId(),\n 'total' => $syncCount,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = ['crm_id' => $crmId];\n\n try {\n $generator = $strategy->fetchOpportunities($parameters);\n $pdOpportunity = $generator->current();\n } catch (ItemNotFoundException | PipedriveException $e) {\n $this->logger->info('[Pipedrive] Failed to sync opportunity', [\n 'crm_id' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n return $this->importOpportunity($pdOpportunity);\n }\n\n /**\n * @inheritdoc\n */\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData->deleted) {\n return null;\n }\n\n if ($crmData->org_id) {\n $orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n $account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($orgId);\n\n if ($account === null) {\n // For some bizarre reason, the org_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);\n\n return null;\n }\n }\n } elseif ($crmData->person_id) {\n // Try to get the organization from the person.\n $personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;\n $contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();\n\n if ($contact === null || $contact->account_id === null) {\n $contact = $this->syncContact($personId);\n\n if ($contact === null) {\n // For some bizarre reason, the person_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);\n\n return null;\n }\n\n if ($contact->account_id === null) {\n $this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());\n\n return null;\n }\n }\n\n $account = $contact->account;\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $crmData->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $closeDate = null;\n if ($crmData->expected_close_date) {\n $closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');\n }\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n $data = [\n 'team_id' => $this->team?->getId(),\n 'account_id' => $account?->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->title, 0, 128),\n 'value' => $crmData->value,\n 'currency_code' => CurrencyFormatter::formatCode($crmData->currency),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData->close_time !== null,\n 'is_won' => $crmData->won_time !== null,\n 'stage_id' => $stage?->getId(),\n 'record_type_id' => $recordType?->getId(),\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdContacts = $this->client->getInstance()->persons()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdContacts->getData() === null) {\n return 0;\n }\n\n foreach ($pdContacts->getData() as $pdContact) {\n // Only sync if previously imported.\n if ($this->hasContact($pdContact->id)) {\n $this->importContact($pdContact);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $pdContact = $this->client->getInstance()->persons()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importContact($pdContact->getData());\n }\n\n private function importContact($crmData): Contact\n {\n $photoPath = null;\n $account = null;\n if ($crmData->org_id) {\n /**\n * Pipedrive API is inconsistent, it may return a string variable, or an object\n */\n $crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n\n $account = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmProviderId)\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmProviderId);\n $photoPath = $this->teamService->generateAvatar(\n $crmData->id,\n $crmData->name,\n );\n } else {\n $photoPath = $account->photo_path;\n }\n }\n\n if ($photoPath === null) {\n $photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Contact::class,\n fileName: (string) $crmData->id,\n avatarText: $crmData->name,\n );\n }\n\n $ownerId = $profile = null;\n if ($crmData->owner_id) {\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n }\n\n $parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);\n\n $mobileNumber = null;\n if (isset($crmData->phone[1])) {\n $mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);\n }\n\n $email = null;\n if (isset($crmData->email[0]->value)) {\n $email = mb_strimwidth($crmData->email[0]->value, 0, 191);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->name ?? '', 0, 100),\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobileNumber ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData->job_title ?? null,\n 'photo_path' => $photoPath,\n 'remotely_created_at' => Carbon::parse($crmData->add_time),\n ];\n\n /** @var Contact */\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n // Not applicable.\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?\\Jiminny\\Models\\Crm\\Profile\n {\n // Not needed yet.\n return null;\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);\n\n /*\n // If they have changed, raise a notification to the owner.\n $team->owner->notify(\n new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)\n );\n */\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (Exception $exception) {\n Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {\n $data = [];\n $params = [\n 'term' => $name,\n 'limit' => $count,\n 'start' => $offset,\n 'item_types' => 'person,organization',\n ];\n\n $objects = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $objects = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n if (empty($objects['items'])) {\n return [];\n }\n\n // Build mapped list.\n foreach ($objects['items'] as $object) {\n $object = $object['item'];\n\n // We only support these object types today.\n if (\\in_array($object['type'], ['person', 'organization']) === false) {\n continue;\n }\n\n $objectType = $object['type'] === 'person' ? 'contact' : 'account';\n $record = [\n 'crmId' => $object['id'],\n 'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),\n 'name' => $object['name'],\n 'industry' => null,\n 'title' => null,\n 'prospectType' => $objectType,\n 'phoneNumbers' => [],\n ];\n\n if (isset($object['organization']['name'])) {\n $record['organization'] = $object['organization']['name'];\n }\n\n if (isset($object['phones'][0])) {\n $parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);\n\n // Add phone number to record.\n if (empty($parsedNumber['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national(null, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n }\n\n $data[] = $record;\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'only_primary_association' => 1,\n 'status' => 'open',\n 'sort' => 'update_time DESC',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = 'add_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = 'add_time ASC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n $params['status'] = 'all_not_deleted';\n }\n\n $pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n if ($pdOpportunities === null) {\n return [];\n }\n\n foreach ($pdOpportunities as $pdOpportunity) {\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $record = [\n 'crmId' => $pdOpportunity->id,\n 'name' => $pdOpportunity->title,\n 'value' => $pdOpportunity->formatted_value,\n 'won' => $pdOpportunity->won_time !== null,\n 'closed' => $pdOpportunity->status !== 'open',\n 'stage' => [\n 'id' => $stage?->id_string ?? '',\n 'name' => $stage?->name ?? '',\n ],\n 'recordType' => [\n 'id' => $recordType?->id_string ?? '',\n 'name' => $recordType?->name ?? '',\n ],\n ];\n\n if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n $pdActivities = null;\n $filters = ['done' => 0];\n switch ($objectType) {\n case 'contact':\n $pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();\n\n break;\n case 'account':\n // Prioritize looking up activities on the deal (which should be linked on the account anyway).\n if ($opportunityId) {\n $pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();\n }\n\n // If no deal activity, fall back to the organization.\n if ($pdActivities === null) {\n $pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();\n }\n\n break;\n }\n\n if ($pdActivities === null) {\n return [];\n }\n\n foreach ($pdActivities as $pdActivity) {\n // Only import active, scheduled tasks in the future.\n if ($pdActivity->active_flag) {\n $due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');\n $data[] = [\n 'crmId' => $pdActivity->id,\n 'subject' => $pdActivity->subject,\n 'due' => Carbon::parse($due)->toIso8601String(),\n 'type' => $pdActivity->type,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $email,\n 'item_types' => 'person',\n 'fields' => 'email',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n $this->logger->info('[Pipedrive] Email match failed', [\n 'email' => $email,\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if (\n ! $contact instanceof Contact\n && ! $account instanceof Account\n ) {\n return null;\n }\n\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n if (count($pdOpportunities) > 0) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember !== false) {\n return null;\n }\n\n $params = [\n 'term' => $phone,\n 'item_types' => 'person,organization',\n 'fields' => 'phone',\n ];\n\n $searchResult = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $searchResult = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {\n return null;\n }\n\n $contact = $this->syncContact($searchResult['items'][0]['item']['id']);\n $account = $contact->account;\n\n $countryCode = $this->getCountryCode($contact, $account);\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function getCountryCode($contact, $account): ?string\n {\n if ($contact && $contact->country_code) {\n return $contact->country_code;\n } elseif ($account && $account->country_code) {\n return $account->country_code;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $name,\n 'item_types' => 'person',\n 'fields' => 'name',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Name match failed', [\n 'name' => $name,\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if ($contact || $account) {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n return false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'person_id' => $activity->hasContact() ? $activity->getContact()->getCrmProviderId() : null,\n 'org_id' => $activity->hasAccount() ? $activity->getAccount()->getCrmProviderId() : null,\n 'deal_id' => $activity->hasOpportunity() ? $activity->getOpportunity()->getCrmProviderId() : null,\n ];\n }\n\n private function buildCallPayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->scheduled_start_time->format('H:i'),\n 'due_date' => $activity->scheduled_start_time->toDateString(),\n 'duration' => gmdate('H:i', $activity->duration),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->fetchCustomFieldData($activity, Field::OBJECT_TASK)\n + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->created_at->format('H:i'),\n 'due_date' => $activity->created_at->toDateString(),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function upsertActivity(Activity $activity, array $data): Activity\n {\n // The activity should be logged under an existing activity.\n if ($activity->hasCrmProviderId()) {\n $existingActivity = $this->client->getActivity($activity->getCrmProviderId());\n\n if ($existingActivity && $existingData = $existingActivity->getData()) {\n $existingData = (array) $existingData;\n $data = $this->updateDescription($existingData, $data);\n $data = $this->updateProspectData($existingData, $data);\n\n // Just update the existing engagement with any fresh details.\n $this->client->updateActivity($activity->getCrmProviderId(), $data);\n }\n } else {\n $pdActivity = $this->client->createActivity($data);\n\n $activity->crm_provider_id = $pdActivity->getData()->id;\n $activity->save();\n }\n\n return $activity;\n }\n\n private function updateDescription(array $crmActivityData, array $payloadData): array\n {\n $crmActivityNote = $crmActivityData['note'] ?? null;\n\n if (! empty($crmActivityNote)) {\n if (! str_contains($crmActivityNote, self::CALL_HEADER)) {\n $payloadData['note'] = $crmActivityNote . \"\\n\\n\" . $payloadData['note'];\n } else {\n $payloadData['note'] = $crmActivityNote;\n }\n }\n\n return $payloadData;\n }\n\n private function updateProspectData($crmActivityData, array $data): array\n {\n $changedData = [];\n if ($crmActivityData['person_id'] && ! isset($data['person_id'])) {\n $changedData['person_id'] = $crmActivityData['person_id'];\n $data['person_id'] = $crmActivityData['person_id'];\n $data['org_id'] = null;\n $data['deal_id'] = null;\n } elseif (isset($data['person_id']) && $data['person_id'] != $crmActivityData['person_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in person_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['person_id'],\n 'crm_activity_data' => $crmActivityData['person_id'],\n ]);\n }\n\n if ($crmActivityData['org_id'] && ! isset($data['org_id'])) {\n $changedData['org_id'] = $crmActivityData['org_id'];\n $data['org_id'] = $crmActivityData['org_id'];\n $data['deal_id'] = null;\n } elseif (isset($data['org_id']) && $data['org_id'] != $crmActivityData['org_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in org_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['org_id'],\n 'crm_activity_data' => $crmActivityData['org_id'],\n ]);\n }\n\n if ($crmActivityData['deal_id'] && ! isset($data['deal_id'])) {\n $changedData['deal_id'] = $crmActivityData['deal_id'];\n $data['deal_id'] = $crmActivityData['deal_id'];\n } elseif (isset($data['deal_id']) && $data['deal_id'] != $crmActivityData['deal_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in deal_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['deal_id'],\n 'crm_activity_data' => $crmActivityData['deal_id'],\n ]);\n }\n\n if (! empty($changedData)) {\n $this->logger->info('[Pipedrive] Updated activity associations', $changedData);\n }\n\n return $data;\n }\n\n private function generateActivityTitle(Activity $activity): string\n {\n if ($activity->hasTitle()) {\n $title = $activity->title;\n } elseif ($activity->playbook_category_id) {\n $title = $activity->category->name;\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n self::CALL_HEADER\n );\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->hasTitle()) {\n // Insert the activity type since there is no native field.\n $description .= sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n $activity->category->name,\n );\n }\n\n if ($activity->isTypeSoftPhone()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">Review in Jiminny</a>'\n . ' ▶️'\n . '</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->type === Activity::TYPE_CONFERENCE) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity type field.\n if (empty($fields['type'])) {\n return null;\n }\n\n if (empty($fields['subject'])) {\n // We need to convert the name correctly.\n $playbook = $this->getPlaybook($activity->getUser());\n $type = $playbook->activityField->values()->where('value', $fields['type'])->first();\n $subject = ($type->label ?? $fields['type']) . ' with ' . $activity->prospect_name;\n } else {\n $subject = $fields['subject'];\n }\n\n $data = [\n 'done' => 0,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_date' => $fields['due_date'] ?? date('Y-m-d'),\n 'due_time' => $fields['due_time'] ?? null,\n 'subject' => $subject,\n 'type' => $fields['type'],\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->activities()->add($data);\n\n // We don't actually create a corresponding activity object on our side yet.\n return $pdActivity->getData()->id;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, self::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'content' => $transcripts,\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->notes()->add($data);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $pdActivity->getData()->id;\n $transcription->save();\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->convertObjectTypeToResource($objectType)->update($objectId, $data);\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n $record = $this->convertObjectTypeToResource($objectType)->find($objectId)->getData();\n\n // We could map the fields requested here before returning.\n return $record ? (array) $record : [];\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case parent::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals();\n\n case parent::OBJECT_CONTACT:\n return $this->client->getInstance()->persons();\n\n case parent::OBJECT_ACCOUNT:\n return $this->client->getInstance()->organizations();\n\n case parent::OBJECT_TASK:\n return $this->client->getInstance()->activities();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \".$objectType.\"');\n }\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, [\n 'stage_id' => $stage->crm_provider_id,\n ]);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->field->crm_provider_id => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n switch ($objectType) {\n case 'account':\n $url = $this->config->crm_base_url . '/organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $this->config->crm_base_url . '/person/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $this->config->crm_base_url . '/deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Pipedrive UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n public function importPipeline(int $pipelineId): ?BusinessProcess\n {\n try {\n $pipeline = $this->client->getInstance()->pipelines()->find($pipelineId)->getData();\n } catch (ItemNotFoundException $exception) {\n return null;\n }\n\n if ($pipeline === null) {\n return null;\n }\n\n return $this->importPipelineData($pipeline);\n }\n\n private function importPipelineData(mixed $pipeline): BusinessProcess\n {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $pipeline->active,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'is_selectable' => $pipeline->active,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n return $businessProcess;\n }\n\n private function importStagesForBusinessProcess(BusinessProcess $businessProcess, ?string $missingId): ?Stage\n {\n $missingStage = null;\n $stages = [];\n $dealStages = $this->client->getInstance()\n ->stages()\n ->all(['pipeline_id' => (int) $businessProcess->crm_provider_id])\n ->getData();\n\n foreach ($dealStages as $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->importStage($dealStage);\n\n if ($missingId !== null && $stage->crm_provider_id == $missingId) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n\n return $missingStage;\n }\n\n private function importStage(mixed $dealStage): Stage\n {\n return $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage->name, 0, 50),\n 'label' => mb_strimwidth($dealStage->name, 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $dealStage->order_nr,\n 'is_selectable' => $dealStage->active_flag,\n 'probability' => $dealStage->deal_probability,\n ]);\n }\n\n private function getBusinessProcesses(string $pipelineId): ?BusinessProcess\n {\n return $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $pipelineId)\n ->first();\n }\n\n private function getStage(?BusinessProcess $businessProcess, string $stageId): ?Stage\n {\n return $businessProcess\n ?->stages()\n ->where('crm_provider_id', $stageId)\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if (! is_numeric($crmProviderId)) {\n $this->logger->warning('[Pipedrive] Invalid activity ID format', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n $activity = $this->client->getActivity($crmProviderId);\n\n return ($activity->active_flag ?? false) === true;\n } catch (HttpNotFoundException) {\n // Activity not found in CRM - this is expected and permanent\n $this->logger->info('[Pipedrive] Activity not found during verification', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Pipedrive;\n\nuse Carbon\\Carbon;\nuse Devio\\Pipedrive\\Exceptions\\ItemNotFoundException;\nuse Devio\\Pipedrive\\Exceptions\\PipedriveException;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\PipedriveInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Events\\Users\\SocialAccountDisconnected;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\SocialAccountTokenInvalidException;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Log;\nuse UnexpectedValueException;\n\nclass Service extends BaseService implements\n PipedriveInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string CALL_HEADER = 'Jiminny Summary';\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)\n {\n parent::__construct();\n\n $this->client = $client;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Pipedrive';\n }\n\n /**\n * @inheritdoc\n */\n public function setUser(User $user): void\n {\n try {\n parent::setUser($user);\n } catch (InvalidArgumentException $exception) {\n // In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.\n if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&\n $exception->getMessage() === 'Required option not passed: \"access_token\"') {\n // Something terrible happened to their token, they need to reconnect.\n $this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);\n\n event(new SocialAccountDisconnected($this->client->oauthAccount));\n }\n\n throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');\n }\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n switch ($fieldType) {\n case Field::TYPE_DATE:\n $value = $internal ? Carbon::parse($fieldValue) : $fieldValue;\n\n break;\n\n default:\n $value = $fieldValue;\n }\n\n return $value;\n }\n\n /**\n * Gets the valid fields for a given Object via the property APIs.\n *\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n switch ($crmObject) {\n case 'task':\n $properties = $this->client->getInstance()->activityFields();\n\n break;\n\n case 'account':\n $properties = $this->client->getInstance()->organizationFields();\n\n break;\n\n case 'contact':\n $properties = $this->client->getInstance()->personFields();\n\n break;\n\n case 'opportunity':\n $properties = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException();\n }\n\n $fields = [];\n\n try {\n $response = $properties->all();\n\n if ($response->isSuccess() === false) {\n throw new Exception($response->getContent(), $response->getStatusCode());\n }\n\n foreach ($response->getData() as $property) {\n $fields[] = ['label' => $property->name, 'name' => $property->key];\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n return;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n $field->description = null;\n $field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($crmField->field_type);\n $field->is_selectable = $crmField->active_flag;\n $field->save();\n }\n }\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'enum':\n case 'stage':\n case 'status':\n return Field::TYPE_PICKLIST;\n\n case 'varchar':\n return Field::TYPE_TEXT;\n\n case 'int':\n case 'double':\n return Field::TYPE_NUMBER;\n\n case 'text':\n return Field::TYPE_TEXTAREA;\n\n case 'monetary':\n return Field::TYPE_CURRENCY;\n\n case Field::TYPE_DATE:\n case Field::TYPE_TIME:\n case Field::TYPE_PHONE:\n return $fieldType;\n\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException('Invalid field type \"' . $field->object_type . '\" for field ' . $field->id . '.');\n }\n\n if ($field->crm_provider_id == 'stage_id') {\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n foreach ($pipelines as $pipeline) {\n $dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();\n foreach ($dealStages as $i => $dealStage) {\n $values = [\n 'value' => $dealStage->id,\n 'label' => $dealStage->name,\n 'sequence' => $i,\n ];\n\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $dealStage->id,\n ], $values);\n }\n }\n\n return $fieldValues;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n // Import all active values.\n if (property_exists($crmField, 'options')) {\n foreach ($crmField->options as $i => $option) {\n $values[] = [\n 'value' => $option->id,\n 'label' => $option->label,\n 'sequence' => $i,\n ];\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n *\n * @throws SocialAccountTokenInvalidException\n * @throws PipedriveException\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // We create a business process to contain the pipeline, and later store all stages against it.\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n\n foreach ($pipelines as $pipeline) {\n $businessProcess = $this->importPipelineData($pipeline);\n\n $stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);\n if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {\n $missingStage = $stage;\n }\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n // Pipedrive doesn't use leads.\n return 0;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n // Pipedrive doesn't use leads.\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdAccounts = $this->client->getInstance()->organizations()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdAccounts->getData() === null) {\n return 0;\n }\n\n foreach ($pdAccounts->getData() as $pdAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($pdAccount->id)) {\n $this->importAccount($pdAccount);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $hsAccount = $this->client->getInstance()->organizations()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importAccount($hsAccount->getData());\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData->country_code;\n if ($countryCode === null && $crmData->address_country) {\n $countryCode = $this->convertCountryNameToCode($crmData->address_country);\n }\n\n $name = $crmData->name;\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n /**\n * Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.\n * These are real samples from API results:\n * { ... owner_id: 23696001, ...}\n * OR\n * {\n * ...\n * owner_id: {\n * active_flag: false,\n * id: 12972717,\n * name: 'name here',\n * value: 12972717\n * }\n * }\n */\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Account::class,\n fileName: (string) $crmData->id,\n avatarText: $name,\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Account */\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {\n $this->importOpportunity($pdOpportunity);\n $syncCount++;\n }\n }\n\n $this->logger->info('[Pipedrive] Sync Opportunities completed', [\n 'team' => $this->team->getId(),\n 'syncCount' => $syncCount,\n ]);\n } catch (Exception $exception) {\n $this->logger->info('[Pipedrive] Failed to sync Opportunities ', [\n 'team' => $this->team->getId(),\n 'params' => $parameters,\n 'strategy' => $strategy,\n 'reason' => $exception->getMessage(),\n 'syncedBeforeFailure' => $syncCount,\n ]);\n }\n\n if ($syncCount > 1000) {\n $this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [\n 'team' => $this->team->getId(),\n 'total' => $syncCount,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = ['crm_id' => $crmId];\n\n try {\n $generator = $strategy->fetchOpportunities($parameters);\n $pdOpportunity = $generator->current();\n } catch (ItemNotFoundException | PipedriveException $e) {\n $this->logger->info('[Pipedrive] Failed to sync opportunity', [\n 'crm_id' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n return $this->importOpportunity($pdOpportunity);\n }\n\n /**\n * @inheritdoc\n */\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData->deleted) {\n return null;\n }\n\n if ($crmData->org_id) {\n $orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n $account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($orgId);\n\n if ($account === null) {\n // For some bizarre reason, the org_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);\n\n return null;\n }\n }\n } elseif ($crmData->person_id) {\n // Try to get the organization from the person.\n $personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;\n $contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();\n\n if ($contact === null || $contact->account_id === null) {\n $contact = $this->syncContact($personId);\n\n if ($contact === null) {\n // For some bizarre reason, the person_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);\n\n return null;\n }\n\n if ($contact->account_id === null) {\n $this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());\n\n return null;\n }\n }\n\n $account = $contact->account;\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $crmData->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $closeDate = null;\n if ($crmData->expected_close_date) {\n $closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');\n }\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n $data = [\n 'team_id' => $this->team?->getId(),\n 'account_id' => $account?->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->title, 0, 128),\n 'value' => $crmData->value,\n 'currency_code' => CurrencyFormatter::formatCode($crmData->currency),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData->close_time !== null,\n 'is_won' => $crmData->won_time !== null,\n 'stage_id' => $stage?->getId(),\n 'record_type_id' => $recordType?->getId(),\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdContacts = $this->client->getInstance()->persons()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdContacts->getData() === null) {\n return 0;\n }\n\n foreach ($pdContacts->getData() as $pdContact) {\n // Only sync if previously imported.\n if ($this->hasContact($pdContact->id)) {\n $this->importContact($pdContact);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $pdContact = $this->client->getInstance()->persons()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importContact($pdContact->getData());\n }\n\n private function importContact($crmData): Contact\n {\n $photoPath = null;\n $account = null;\n if ($crmData->org_id) {\n /**\n * Pipedrive API is inconsistent, it may return a string variable, or an object\n */\n $crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n\n $account = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmProviderId)\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmProviderId);\n $photoPath = $this->teamService->generateAvatar(\n $crmData->id,\n $crmData->name,\n );\n } else {\n $photoPath = $account->photo_path;\n }\n }\n\n if ($photoPath === null) {\n $photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Contact::class,\n fileName: (string) $crmData->id,\n avatarText: $crmData->name,\n );\n }\n\n $ownerId = $profile = null;\n if ($crmData->owner_id) {\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n }\n\n $parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);\n\n $mobileNumber = null;\n if (isset($crmData->phone[1])) {\n $mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);\n }\n\n $email = null;\n if (isset($crmData->email[0]->value)) {\n $email = mb_strimwidth($crmData->email[0]->value, 0, 191);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->name ?? '', 0, 100),\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobileNumber ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData->job_title ?? null,\n 'photo_path' => $photoPath,\n 'remotely_created_at' => Carbon::parse($crmData->add_time),\n ];\n\n /** @var Contact */\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n // Not applicable.\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?\\Jiminny\\Models\\Crm\\Profile\n {\n // Not needed yet.\n return null;\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);\n\n /*\n // If they have changed, raise a notification to the owner.\n $team->owner->notify(\n new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)\n );\n */\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (Exception $exception) {\n Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {\n $data = [];\n $params = [\n 'term' => $name,\n 'limit' => $count,\n 'start' => $offset,\n 'item_types' => 'person,organization',\n ];\n\n $objects = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $objects = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n if (empty($objects['items'])) {\n return [];\n }\n\n // Build mapped list.\n foreach ($objects['items'] as $object) {\n $object = $object['item'];\n\n // We only support these object types today.\n if (\\in_array($object['type'], ['person', 'organization']) === false) {\n continue;\n }\n\n $objectType = $object['type'] === 'person' ? 'contact' : 'account';\n $record = [\n 'crmId' => $object['id'],\n 'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),\n 'name' => $object['name'],\n 'industry' => null,\n 'title' => null,\n 'prospectType' => $objectType,\n 'phoneNumbers' => [],\n ];\n\n if (isset($object['organization']['name'])) {\n $record['organization'] = $object['organization']['name'];\n }\n\n if (isset($object['phones'][0])) {\n $parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);\n\n // Add phone number to record.\n if (empty($parsedNumber['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national(null, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n }\n\n $data[] = $record;\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'only_primary_association' => 1,\n 'status' => 'open',\n 'sort' => 'update_time DESC',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = 'add_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = 'add_time ASC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n $params['status'] = 'all_not_deleted';\n }\n\n $pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n if ($pdOpportunities === null) {\n return [];\n }\n\n foreach ($pdOpportunities as $pdOpportunity) {\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $record = [\n 'crmId' => $pdOpportunity->id,\n 'name' => $pdOpportunity->title,\n 'value' => $pdOpportunity->formatted_value,\n 'won' => $pdOpportunity->won_time !== null,\n 'closed' => $pdOpportunity->status !== 'open',\n 'stage' => [\n 'id' => $stage?->id_string ?? '',\n 'name' => $stage?->name ?? '',\n ],\n 'recordType' => [\n 'id' => $recordType?->id_string ?? '',\n 'name' => $recordType?->name ?? '',\n ],\n ];\n\n if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n $pdActivities = null;\n $filters = ['done' => 0];\n switch ($objectType) {\n case 'contact':\n $pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();\n\n break;\n case 'account':\n // Prioritize looking up activities on the deal (which should be linked on the account anyway).\n if ($opportunityId) {\n $pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();\n }\n\n // If no deal activity, fall back to the organization.\n if ($pdActivities === null) {\n $pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();\n }\n\n break;\n }\n\n if ($pdActivities === null) {\n return [];\n }\n\n foreach ($pdActivities as $pdActivity) {\n // Only import active, scheduled tasks in the future.\n if ($pdActivity->active_flag) {\n $due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');\n $data[] = [\n 'crmId' => $pdActivity->id,\n 'subject' => $pdActivity->subject,\n 'due' => Carbon::parse($due)->toIso8601String(),\n 'type' => $pdActivity->type,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $email,\n 'item_types' => 'person',\n 'fields' => 'email',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n $this->logger->info('[Pipedrive] Email match failed', [\n 'email' => $email,\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if (\n ! $contact instanceof Contact\n && ! $account instanceof Account\n ) {\n return null;\n }\n\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n if (count($pdOpportunities) > 0) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember !== false) {\n return null;\n }\n\n $params = [\n 'term' => $phone,\n 'item_types' => 'person,organization',\n 'fields' => 'phone',\n ];\n\n $searchResult = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $searchResult = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {\n return null;\n }\n\n $contact = $this->syncContact($searchResult['items'][0]['item']['id']);\n $account = $contact->account;\n\n $countryCode = $this->getCountryCode($contact, $account);\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function getCountryCode($contact, $account): ?string\n {\n if ($contact && $contact->country_code) {\n return $contact->country_code;\n } elseif ($account && $account->country_code) {\n return $account->country_code;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $name,\n 'item_types' => 'person',\n 'fields' => 'name',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Name match failed', [\n 'name' => $name,\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if ($contact || $account) {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n return false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'person_id' => $activity->hasContact() ? $activity->getContact()->getCrmProviderId() : null,\n 'org_id' => $activity->hasAccount() ? $activity->getAccount()->getCrmProviderId() : null,\n 'deal_id' => $activity->hasOpportunity() ? $activity->getOpportunity()->getCrmProviderId() : null,\n ];\n }\n\n private function buildCallPayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->scheduled_start_time->format('H:i'),\n 'due_date' => $activity->scheduled_start_time->toDateString(),\n 'duration' => gmdate('H:i', $activity->duration),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->fetchCustomFieldData($activity, Field::OBJECT_TASK)\n + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->created_at->format('H:i'),\n 'due_date' => $activity->created_at->toDateString(),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function upsertActivity(Activity $activity, array $data): Activity\n {\n // The activity should be logged under an existing activity.\n if ($activity->hasCrmProviderId()) {\n $existingActivity = $this->client->getActivity($activity->getCrmProviderId());\n\n if ($existingActivity && $existingData = $existingActivity->getData()) {\n $existingData = (array) $existingData;\n $data = $this->updateDescription($existingData, $data);\n $data = $this->updateProspectData($existingData, $data);\n\n // Just update the existing engagement with any fresh details.\n $this->client->updateActivity($activity->getCrmProviderId(), $data);\n }\n } else {\n $pdActivity = $this->client->createActivity($data);\n\n $activity->crm_provider_id = $pdActivity->getData()->id;\n $activity->save();\n }\n\n return $activity;\n }\n\n private function updateDescription(array $crmActivityData, array $payloadData): array\n {\n $crmActivityNote = $crmActivityData['note'] ?? null;\n\n if (! empty($crmActivityNote)) {\n if (! str_contains($crmActivityNote, self::CALL_HEADER)) {\n $payloadData['note'] = $crmActivityNote . \"\\n\\n\" . $payloadData['note'];\n } else {\n $payloadData['note'] = $crmActivityNote;\n }\n }\n\n return $payloadData;\n }\n\n private function updateProspectData($crmActivityData, array $data): array\n {\n $changedData = [];\n if ($crmActivityData['person_id'] && ! isset($data['person_id'])) {\n $changedData['person_id'] = $crmActivityData['person_id'];\n $data['person_id'] = $crmActivityData['person_id'];\n $data['org_id'] = null;\n $data['deal_id'] = null;\n } elseif (isset($data['person_id']) && $data['person_id'] != $crmActivityData['person_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in person_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['person_id'],\n 'crm_activity_data' => $crmActivityData['person_id'],\n ]);\n }\n\n if ($crmActivityData['org_id'] && ! isset($data['org_id'])) {\n $changedData['org_id'] = $crmActivityData['org_id'];\n $data['org_id'] = $crmActivityData['org_id'];\n $data['deal_id'] = null;\n } elseif (isset($data['org_id']) && $data['org_id'] != $crmActivityData['org_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in org_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['org_id'],\n 'crm_activity_data' => $crmActivityData['org_id'],\n ]);\n }\n\n if ($crmActivityData['deal_id'] && ! isset($data['deal_id'])) {\n $changedData['deal_id'] = $crmActivityData['deal_id'];\n $data['deal_id'] = $crmActivityData['deal_id'];\n } elseif (isset($data['deal_id']) && $data['deal_id'] != $crmActivityData['deal_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in deal_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['deal_id'],\n 'crm_activity_data' => $crmActivityData['deal_id'],\n ]);\n }\n\n if (! empty($changedData)) {\n $this->logger->info('[Pipedrive] Updated activity associations', $changedData);\n }\n\n return $data;\n }\n\n private function generateActivityTitle(Activity $activity): string\n {\n if ($activity->hasTitle()) {\n $title = $activity->title;\n } elseif ($activity->playbook_category_id) {\n $title = $activity->category->name;\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n self::CALL_HEADER\n );\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->hasTitle()) {\n // Insert the activity type since there is no native field.\n $description .= sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n $activity->category->name,\n );\n }\n\n if ($activity->isTypeSoftPhone()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">Review in Jiminny</a>'\n . ' ▶️'\n . '</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->type === Activity::TYPE_CONFERENCE) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity type field.\n if (empty($fields['type'])) {\n return null;\n }\n\n if (empty($fields['subject'])) {\n // We need to convert the name correctly.\n $playbook = $this->getPlaybook($activity->getUser());\n $type = $playbook->activityField->values()->where('value', $fields['type'])->first();\n $subject = ($type->label ?? $fields['type']) . ' with ' . $activity->prospect_name;\n } else {\n $subject = $fields['subject'];\n }\n\n $data = [\n 'done' => 0,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_date' => $fields['due_date'] ?? date('Y-m-d'),\n 'due_time' => $fields['due_time'] ?? null,\n 'subject' => $subject,\n 'type' => $fields['type'],\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->activities()->add($data);\n\n // We don't actually create a corresponding activity object on our side yet.\n return $pdActivity->getData()->id;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, self::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'content' => $transcripts,\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->notes()->add($data);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $pdActivity->getData()->id;\n $transcription->save();\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->convertObjectTypeToResource($objectType)->update($objectId, $data);\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n $record = $this->convertObjectTypeToResource($objectType)->find($objectId)->getData();\n\n // We could map the fields requested here before returning.\n return $record ? (array) $record : [];\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case parent::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals();\n\n case parent::OBJECT_CONTACT:\n return $this->client->getInstance()->persons();\n\n case parent::OBJECT_ACCOUNT:\n return $this->client->getInstance()->organizations();\n\n case parent::OBJECT_TASK:\n return $this->client->getInstance()->activities();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \".$objectType.\"');\n }\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, [\n 'stage_id' => $stage->crm_provider_id,\n ]);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->field->crm_provider_id => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n switch ($objectType) {\n case 'account':\n $url = $this->config->crm_base_url . '/organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $this->config->crm_base_url . '/person/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $this->config->crm_base_url . '/deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Pipedrive UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n public function importPipeline(int $pipelineId): ?BusinessProcess\n {\n try {\n $pipeline = $this->client->getInstance()->pipelines()->find($pipelineId)->getData();\n } catch (ItemNotFoundException $exception) {\n return null;\n }\n\n if ($pipeline === null) {\n return null;\n }\n\n return $this->importPipelineData($pipeline);\n }\n\n private function importPipelineData(mixed $pipeline): BusinessProcess\n {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $pipeline->active,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'is_selectable' => $pipeline->active,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n return $businessProcess;\n }\n\n private function importStagesForBusinessProcess(BusinessProcess $businessProcess, ?string $missingId): ?Stage\n {\n $missingStage = null;\n $stages = [];\n $dealStages = $this->client->getInstance()\n ->stages()\n ->all(['pipeline_id' => (int) $businessProcess->crm_provider_id])\n ->getData();\n\n foreach ($dealStages as $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->importStage($dealStage);\n\n if ($missingId !== null && $stage->crm_provider_id == $missingId) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n\n return $missingStage;\n }\n\n private function importStage(mixed $dealStage): Stage\n {\n return $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage->name, 0, 50),\n 'label' => mb_strimwidth($dealStage->name, 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $dealStage->order_nr,\n 'is_selectable' => $dealStage->active_flag,\n 'probability' => $dealStage->deal_probability,\n ]);\n }\n\n private function getBusinessProcesses(string $pipelineId): ?BusinessProcess\n {\n return $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $pipelineId)\n ->first();\n }\n\n private function getStage(?BusinessProcess $businessProcess, string $stageId): ?Stage\n {\n return $businessProcess\n ?->stages()\n ->where('crm_provider_id', $stageId)\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if (! is_numeric($crmProviderId)) {\n $this->logger->warning('[Pipedrive] Invalid activity ID format', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n $activity = $this->client->getActivity($crmProviderId);\n\n return ($activity->active_flag ?? false) === true;\n } catch (HttpNotFoundException) {\n // Activity not found in CRM - this is expected and permanent\n $this->logger->info('[Pipedrive] Activity not found during verification', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"app ~/jiminny/app","depth":6,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":".circleci","depth":7,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":".cursor","depth":7,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":".github","depth":7,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":".sonarlint","depth":7,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":".vscode","depth":7,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":".windsurf","depth":7,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"app, sources root","depth":7,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Actions","depth":8,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Component","depth":8,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Acl","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"ActionItems","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Activity","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"ActivityAnalytics","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"ActivitySearch","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"AiActivityType","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"AiAutomation","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"AiCallScoring","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"AskAnything","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Dtos, folder","depth":10,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Events, folder","depth":10,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"AskAnythingPromptService.php","depth":10,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"HistoryService.php, class","depth":10,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"AskJiminnyAi","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"AWS","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"BillingManagement","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Cache","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"CoachingFeedback","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"Country","depth":9,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"CustomerApi","depth":9,"on_screen":false,"role_description":"text"}]...
|
3865544371963712397
|
-7980155751442543530
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3
9
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Pipedrive;
use Carbon\Carbon;
use Devio\Pipedrive\Exceptions\ItemNotFoundException;
use Devio\Pipedrive\Exceptions\PipedriveException;
use Exception;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\PipedriveInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Events\Users\SocialAccountDisconnected;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\SocialAccountTokenInvalidException;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Log;
use UnexpectedValueException;
class Service extends BaseService implements
PipedriveInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string CALL_HEADER = 'Jiminny Summary';
/**
* @var ClientInterface|Client
*/
protected $client;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)
{
parent::__construct();
$this->client = $client;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Pipedrive';
}
/**
* @inheritdoc
*/
public function setUser(User $user): void
{
try {
parent::setUser($user);
} catch (InvalidArgumentException $exception) {
// In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.
if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&
$exception->getMessage() === 'Required option not passed: "access_token"') {
// Something terrible happened to their token, they need to reconnect.
$this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);
event(new SocialAccountDisconnected($this->client->oauthAccount));
}
throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');
}
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
switch ($fieldType) {
case Field::TYPE_DATE:
$value = $internal ? Carbon::parse($fieldValue) : $fieldValue;
break;
default:
$value = $fieldValue;
}
return $value;
}
/**
* Gets the valid fields for a given Object via the property APIs.
*
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
switch ($crmObject) {
case 'task':
$properties = $this->client->getInstance()->activityFields();
break;
case 'account':
$properties = $this->client->getInstance()->organizationFields();
break;
case 'contact':
$properties = $this->client->getInstance()->personFields();
break;
case 'opportunity':
$properties = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException();
}
$fields = [];
try {
$response = $properties->all();
if ($response->isSuccess() === false) {
throw new Exception($response->getContent(), $response->getStatusCode());
}
foreach ($response->getData() as $property) {
$fields[] = ['label' => $property->name, 'name' => $property->key];
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
return;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
$field->description = null;
$field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($crmField->field_type);
$field->is_selectable = $crmField->active_flag;
$field->save();
}
}
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'enum':
case 'stage':
case 'status':
return Field::TYPE_PICKLIST;
case 'varchar':
return Field::TYPE_TEXT;
case 'int':
case 'double':
return Field::TYPE_NUMBER;
case 'text':
return Field::TYPE_TEXTAREA;
case 'monetary':
return Field::TYPE_CURRENCY;
case Field::TYPE_DATE:
case Field::TYPE_TIME:
case Field::TYPE_PHONE:
return $fieldType;
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException('Invalid field type "' . $field->object_type . '" for field ' . $field->id . '.');
}
if ($field->crm_provider_id == 'stage_id') {
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();
foreach ($dealStages as $i => $dealStage) {
$values = [
'value' => $dealStage->id,
'label' => $dealStage->name,
'sequence' => $i,
];
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $dealStage->id,
], $values);
}
}
return $fieldValues;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
// Import all active values.
if (property_exists($crmField, 'options')) {
foreach ($crmField->options as $i => $option) {
$values[] = [
'value' => $option->id,
'label' => $option->label,
'sequence' => $i,
];
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
return $fieldValues;
}
/**
* @inheritdoc
*
* @throws SocialAccountTokenInvalidException
* @throws PipedriveException
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// We create a business process to contain the pipeline, and later store all stages against it.
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$businessProcess = $this->importPipelineData($pipeline);
$stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);
if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {
$missingStage = $stage;
}
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
// Pipedrive doesn't use leads.
return 0;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
// Pipedrive doesn't use leads.
return null;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdAccounts = $this->client->getInstance()->organizations()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdAccounts->getData() === null) {
return 0;
}
foreach ($pdAccounts->getData() as $pdAccount) {
// Only sync if previously imported.
if ($this->hasAccount($pdAccount->id)) {
$this->importAccount($pdAccount);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
try {
$hsAccount = $this->client->getInstance()->organizations()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);
}
return $this->importAccount($hsAccount->getData());
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = $crmData->country_code;
if ($countryCode === null && $crmData->address_country) {
$countryCode = $this->convertCountryNameToCode($crmData->address_country);
}
$name = $crmData->name;
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
/**
* Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.
* These are real samples from API results:
* { ... owner_id: 23696001, ...}
* OR
* {
* ...
* owner_id: {
* active_flag: false,
* id: 12972717,
* name: 'name here',
* value: 12972717
* }
* }
*/
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Account::class,
fileName: (string) $crmData->id,
avatarText: $name,
),
'country_code' => $countryCode,
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Account */
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {
$this->importOpportunity($pdOpportunity);
$syncCount++;
}
}
$this->logger->info('[Pipedrive] Sync Opportunities completed', [
'team' => $this->team->getId(),
'syncCount' => $syncCount,
]);
} catch (Exception $exception) {
$this->logger->info('[Pipedrive] Failed to sync Opportunities ', [
'team' => $this->team->getId(),
'params' => $parameters,
'strategy' => $strategy,
'reason' => $exception->getMessage(),
'syncedBeforeFailure' => $syncCount,
]);
}
if ($syncCount > 1000) {
$this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [
'team' => $this->team->getId(),
'total' => $syncCount,
]);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = ['crm_id' => $crmId];
try {
$generator = $strategy->fetchOpportunities($parameters);
$pdOpportunity = $generator->current();
} catch (ItemNotFoundException | PipedriveException $e) {
$this->logger->info('[Pipedrive] Failed to sync opportunity', [
'crm_id' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
return $this->importOpportunity($pdOpportunity);
}
/**
* @inheritdoc
*/
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData->deleted) {
return null;
}
if ($crmData->org_id) {
$orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();
if ($account === null) {
$account = $this->syncAccount($orgId);
if ($account === null) {
// For some bizarre reason, the org_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);
return null;
}
}
} elseif ($crmData->person_id) {
// Try to get the organization from the person.
$personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;
$contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();
if ($contact === null || $contact->account_id === null) {
$contact = $this->syncContact($personId);
if ($contact === null) {
// For some bizarre reason, the person_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);
return null;
}
if ($contact->account_id === null) {
$this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());
return null;
}
}
$account = $contact->account;
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $crmData->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$closeDate = null;
if ($crmData->expected_close_date) {
$closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');
}
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
$data = [
'team_id' => $this->team?->getId(),
'account_id' => $account?->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->title, 0, 128),
'value' => $crmData->value,
'currency_code' => CurrencyFormatter::formatCode($crmData->currency),
'close_date' => $closeDate,
'is_closed' => $crmData->close_time !== null,
'is_won' => $crmData->won_time !== null,
'stage_id' => $stage?->getId(),
'record_type_id' => $recordType?->getId(),
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Opportunity $opportunity */
$opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
// import external fields into crm_field_data if present
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdContacts = $this->client->getInstance()->persons()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdContacts->getData() === null) {
return 0;
}
foreach ($pdContacts->getData() as $pdContact) {
// Only sync if previously imported.
if ($this->hasContact($pdContact->id)) {
$this->importContact($pdContact);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
try {
$pdContact = $this->client->getInstance()->persons()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);
}
return $this->importContact($pdContact->getData());
}
private function importContact($crmData): Contact
{
$photoPath = null;
$account = null;
if ($crmData->org_id) {
/**
* Pipedrive API is inconsistent, it may return a string variable, or an object
*/
$crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config
->accounts()
->where('crm_provider_id', $crmProviderId)
->first();
if ($account === null) {
$account = $this->syncAccount($crmProviderId);
$photoPath = $this->teamService->generateAvatar(
$crmData->id,
$crmData->name,
);
} else {
$photoPath = $account->photo_path;
}
}
if ($photoPath === null) {
$photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Contact::class,
fileName: (string) $crmData->id,
avatarText: $crmData->name,
);
}
$ownerId = $profile = null;
if ($crmData->owner_id) {
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
}
$parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);
$mobileNumber = null;
if (isset($crmData->phone[1])) {
$mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);
}
$email = null;
if (isset($crmData->email[0]->value)) {
$email = mb_strimwidth($crmData->email[0]->value, 0, 191);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->name ?? '', 0, 100),
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobileNumber ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData->job_title ?? null,
'photo_path' => $photoPath,
'remotely_created_at' => Carbon::parse($crmData->add_time),
];
/** @var Contact */
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
// Not applicable.
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?\Jiminny\Models\Crm\Profile
{
// Not needed yet.
return null;
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);
/*
// If they have changed, raise a notification to the owner.
$team->owner->notify(
new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)
);
*/
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (Exception $exception) {
Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {
$data = [];
$params = [
'term' => $name,
'limit' => $count,
'start' => $offset,
'item_types' => 'person,organization',
];
$objects = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$objects = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
if (empty($objects['items'])) {
return [];
}
// Build mapped list.
foreach ($objects['items'] as $object) {
$object = $object['item'];
// We only support these object types today.
if (\in_array($object['type'], ['person', 'organization']) === false) {
continue;
}
$objectType = $object['type'] === 'person' ? 'contact' : 'account';
$record = [
'crmId' => $object['id'],
'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),
'name' => $object['name'],
'industry' => null,
'title' => null,
'prospectType' => $objectType,
'phoneNumbers' => [],
];
if (isset($object['organization']['name'])) {
$record['organization'] = $object['organization']['name'];
}
if (isset($object['phones'][0])) {
$parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);
// Add phone number to record.
if (empty($parsedNumber['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $parsedNumber['phone'],
'nationalFormat' => phone_national(null, $parsedNumber['phone']),
'type' => 'phone',
];
}
}
$data[] = $record;
}
return $data;
});
return $data;
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'only_primary_association' => 1,
'status' => 'open',
'sort' => 'update_time DESC',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = 'add_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = 'add_time ASC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
$params['status'] = 'all_not_deleted';
}
$pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
if ($pdOpportunities === null) {
return [];
}
foreach ($pdOpportunities as $pdOpportunity) {
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$record = [
'crmId' => $pdOpportunity->id,
'name' => $pdOpportunity->title,
'value' => $pdOpportunity->formatted_value,
'won' => $pdOpportunity->won_time !== null,
'closed' => $pdOpportunity->status !== 'open',
'stage' => [
'id' => $stage?->id_string ?? '',
'name' => $stage?->name ?? '',
],
'recordType' => [
'id' => $recordType?->id_string ?? '',
'name' => $recordType?->name ?? '',
],
];
if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
$pdActivities = null;
$filters = ['done' => 0];
switch ($objectType) {
case 'contact':
$pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();
break;
case 'account':
// Prioritize looking up activities on the deal (which should be linked on the account anyway).
if ($opportunityId) {
$pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();
}
// If no deal activity, fall back to the organization.
if ($pdActivities === null) {
$pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();
}
break;
}
if ($pdActivities === null) {
return [];
}
foreach ($pdActivities as $pdActivity) {
// Only import active, scheduled tasks in the future.
if ($pdActivity->active_flag) {
$due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');
$data[] = [
'crmId' => $pdActivity->id,
'subject' => $pdActivity->subject,
'due' => Carbon::parse($due)->toIso8601String(),
'type' => $pdActivity->type,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contact = null;
$account = null;
$params = [
'term' => $email,
'item_types' => 'person',
'fields' => 'email',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
$this->logger->info('[Pipedrive] Email match failed', [
'email' => $email,
'reason' => $exception->getMessage(),
]);
return null;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if (
! $contact instanceof Contact
&& ! $account instanceof Account
) {
return null;
}
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (count($pdOpportunities) > 0) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
// Check if the user is internal.
$teamMember = $this->team->users()->where('phone', $phone)->exists();
// Skip the attendee if internal.
if ($teamMember !== false) {
return null;
}
$params = [
'term' => $phone,
'item_types' => 'person,organization',
'fields' => 'phone',
];
$searchResult = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$searchResult = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Phone match failed', [
'phone' => $phone,
'reason' => $e->getMessage(),
]);
return null;
}
if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {
return null;
}
$contact = $this->syncContact($searchResult['items'][0]['item']['id']);
$account = $contact->account;
$countryCode = $this->getCountryCode($contact, $account);
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function getCountryCode($contact, $account): ?string
{
if ($contact && $contact->country_code) {
return $contact->country_code;
} elseif ($account && $account->country_code) {
return $account->country_code;
}
return null;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {
$contact = null;
$account = null;
$params = [
'term' => $name,
'item_types' => 'person',
'fields' => 'name',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Name match failed', [
'name' => $name,
'reason' => $e->getMessage(),
]);
return false;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if ($contact || $account) {
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
return false;
});
return is_array($result) ? $result : null;
}
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->type) {
case Activity::TYPE_CONFERENCE:
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildCallPayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45286
|
1624
|
17
|
2026-05-14T14:29:05.034858+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768945034_m2.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3
9
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Pipedrive;
use Carbon\Carbon;
use Devio\Pipedrive\Exceptions\ItemNotFoundException;
use Devio\Pipedrive\Exceptions\PipedriveException;
use Exception;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\PipedriveInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Events\Users\SocialAccountDisconnected;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\SocialAccountTokenInvalidException;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Log;
use UnexpectedValueException;
class Service extends BaseService implements
PipedriveInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string CALL_HEADER = 'Jiminny Summary';
/**
* @var ClientInterface|Client
*/
protected $client;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)
{
parent::__construct();
$this->client = $client;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Pipedrive';
}
/**
* @inheritdoc
*/
public function setUser(User $user): void
{
try {
parent::setUser($user);
} catch (InvalidArgumentException $exception) {
// In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.
if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&
$exception->getMessage() === 'Required option not passed: "access_token"') {
// Something terrible happened to their token, they need to reconnect.
$this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);
event(new SocialAccountDisconnected($this->client->oauthAccount));
}
throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');
}
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
switch ($fieldType) {
case Field::TYPE_DATE:
$value = $internal ? Carbon::parse($fieldValue) : $fieldValue;
break;
default:
$value = $fieldValue;
}
return $value;
}
/**
* Gets the valid fields for a given Object via the property APIs.
*
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
switch ($crmObject) {
case 'task':
$properties = $this->client->getInstance()->activityFields();
break;
case 'account':
$properties = $this->client->getInstance()->organizationFields();
break;
case 'contact':
$properties = $this->client->getInstance()->personFields();
break;
case 'opportunity':
$properties = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException();
}
$fields = [];
try {
$response = $properties->all();
if ($response->isSuccess() === false) {
throw new Exception($response->getContent(), $response->getStatusCode());
}
foreach ($response->getData() as $property) {
$fields[] = ['label' => $property->name, 'name' => $property->key];
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
return;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
$field->description = null;
$field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($crmField->field_type);
$field->is_selectable = $crmField->active_flag;
$field->save();
}
}
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'enum':
case 'stage':
case 'status':
return Field::TYPE_PICKLIST;
case 'varchar':
return Field::TYPE_TEXT;
case 'int':
case 'double':
return Field::TYPE_NUMBER;
case 'text':
return Field::TYPE_TEXTAREA;
case 'monetary':
return Field::TYPE_CURRENCY;
case Field::TYPE_DATE:
case Field::TYPE_TIME:
case Field::TYPE_PHONE:
return $fieldType;
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException('Invalid field type "' . $field->object_type . '" for field ' . $field->id . '.');
}
if ($field->crm_provider_id == 'stage_id') {
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();
foreach ($dealStages as $i => $dealStage) {
$values = [
'value' => $dealStage->id,
'label' => $dealStage->name,
'sequence' => $i,
];
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $dealStage->id,
], $values);
}
}
return $fieldValues;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
// Import all active values.
if (property_exists($crmField, 'options')) {
foreach ($crmField->options as $i => $option) {
$values[] = [
'value' => $option->id,
'label' => $option->label,
'sequence' => $i,
];
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
return $fieldValues;
}
/**
* @inheritdoc
*
* @throws SocialAccountTokenInvalidException
* @throws PipedriveException
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// We create a business process to contain the pipeline, and later store all stages against it.
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$businessProcess = $this->importPipelineData($pipeline);
$stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);
if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {
$missingStage = $stage;
}
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
// Pipedrive doesn't use leads.
return 0;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
// Pipedrive doesn't use leads.
return null;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdAccounts = $this->client->getInstance()->organizations()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdAccounts->getData() === null) {
return 0;
}
foreach ($pdAccounts->getData() as $pdAccount) {
// Only sync if previously imported.
if ($this->hasAccount($pdAccount->id)) {
$this->importAccount($pdAccount);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
try {
$hsAccount = $this->client->getInstance()->organizations()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);
}
return $this->importAccount($hsAccount->getData());
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = $crmData->country_code;
if ($countryCode === null && $crmData->address_country) {
$countryCode = $this->convertCountryNameToCode($crmData->address_country);
}
$name = $crmData->name;
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
/**
* Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.
* These are real samples from API results:
* { ... owner_id: 23696001, ...}
* OR
* {
* ...
* owner_id: {
* active_flag: false,
* id: 12972717,
* name: 'name here',
* value: 12972717
* }
* }
*/
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Account::class,
fileName: (string) $crmData->id,
avatarText: $name,
),
'country_code' => $countryCode,
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Account */
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {
$this->importOpportunity($pdOpportunity);
$syncCount++;
}
}
$this->logger->info('[Pipedrive] Sync Opportunities completed', [
'team' => $this->team->getId(),
'syncCount' => $syncCount,
]);
} catch (Exception $exception) {
$this->logger->info('[Pipedrive] Failed to sync Opportunities ', [
'team' => $this->team->getId(),
'params' => $parameters,
'strategy' => $strategy,
'reason' => $exception->getMessage(),
'syncedBeforeFailure' => $syncCount,
]);
}
if ($syncCount > 1000) {
$this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [
'team' => $this->team->getId(),
'total' => $syncCount,
]);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = ['crm_id' => $crmId];
try {
$generator = $strategy->fetchOpportunities($parameters);
$pdOpportunity = $generator->current();
} catch (ItemNotFoundException | PipedriveException $e) {
$this->logger->info('[Pipedrive] Failed to sync opportunity', [
'crm_id' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
return $this->importOpportunity($pdOpportunity);
}
/**
* @inheritdoc
*/
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData->deleted) {
return null;
}
if ($crmData->org_id) {
$orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();
if ($account === null) {
$account = $this->syncAccount($orgId);
if ($account === null) {
// For some bizarre reason, the org_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);
return null;
}
}
} elseif ($crmData->person_id) {
// Try to get the organization from the person.
$personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;
$contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();
if ($contact === null || $contact->account_id === null) {
$contact = $this->syncContact($personId);
if ($contact === null) {
// For some bizarre reason, the person_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);
return null;
}
if ($contact->account_id === null) {
$this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());
return null;
}
}
$account = $contact->account;
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $crmData->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$closeDate = null;
if ($crmData->expected_close_date) {
$closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');
}
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
$data = [
'team_id' => $this->team?->getId(),
'account_id' => $account?->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->title, 0, 128),
'value' => $crmData->value,
'currency_code' => CurrencyFormatter::formatCode($crmData->currency),
'close_date' => $closeDate,
'is_closed' => $crmData->close_time !== null,
'is_won' => $crmData->won_time !== null,
'stage_id' => $stage?->getId(),
'record_type_id' => $recordType?->getId(),
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Opportunity $opportunity */
$opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
// import external fields into crm_field_data if present
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdContacts = $this->client->getInstance()->persons()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdContacts->getData() === null) {
return 0;
}
foreach ($pdContacts->getData() as $pdContact) {
// Only sync if previously imported.
if ($this->hasContact($pdContact->id)) {
$this->importContact($pdContact);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
try {
$pdContact = $this->client->getInstance()->persons()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);
}
return $this->importContact($pdContact->getData());
}
private function importContact($crmData): Contact
{
$photoPath = null;
$account = null;
if ($crmData->org_id) {
/**
* Pipedrive API is inconsistent, it may return a string variable, or an object
*/
$crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config
->accounts()
->where('crm_provider_id', $crmProviderId)
->first();
if ($account === null) {
$account = $this->syncAccount($crmProviderId);
$photoPath = $this->teamService->generateAvatar(
$crmData->id,
$crmData->name,
);
} else {
$photoPath = $account->photo_path;
}
}
if ($photoPath === null) {
$photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Contact::class,
fileName: (string) $crmData->id,
avatarText: $crmData->name,
);
}
$ownerId = $profile = null;
if ($crmData->owner_id) {
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
}
$parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);
$mobileNumber = null;
if (isset($crmData->phone[1])) {
$mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);
}
$email = null;
if (isset($crmData->email[0]->value)) {
$email = mb_strimwidth($crmData->email[0]->value, 0, 191);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->name ?? '', 0, 100),
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobileNumber ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData->job_title ?? null,
'photo_path' => $photoPath,
'remotely_created_at' => Carbon::parse($crmData->add_time),
];
/** @var Contact */
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
// Not applicable.
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?\Jiminny\Models\Crm\Profile
{
// Not needed yet.
return null;
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);
/*
// If they have changed, raise a notification to the owner.
$team->owner->notify(
new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)
);
*/
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (Exception $exception) {
Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {
$data = [];
$params = [
'term' => $name,
'limit' => $count,
'start' => $offset,
'item_types' => 'person,organization',
];
$objects = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$objects = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
if (empty($objects['items'])) {
return [];
}
// Build mapped list.
foreach ($objects['items'] as $object) {
$object = $object['item'];
// We only support these object types today.
if (\in_array($object['type'], ['person', 'organization']) === false) {
continue;
}
$objectType = $object['type'] === 'person' ? 'contact' : 'account';
$record = [
'crmId' => $object['id'],
'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),
'name' => $object['name'],
'industry' => null,
'title' => null,
'prospectType' => $objectType,
'phoneNumbers' => [],
];
if (isset($object['organization']['name'])) {
$record['organization'] = $object['organization']['name'];
}
if (isset($object['phones'][0])) {
$parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);
// Add phone number to record.
if (empty($parsedNumber['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $parsedNumber['phone'],
'nationalFormat' => phone_national(null, $parsedNumber['phone']),
'type' => 'phone',
];
}
}
$data[] = $record;
}
return $data;
});
return $data;
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'only_primary_association' => 1,
'status' => 'open',
'sort' => 'update_time DESC',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = 'add_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = 'add_time ASC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
$params['status'] = 'all_not_deleted';
}
$pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
if ($pdOpportunities === null) {
return [];
}
foreach ($pdOpportunities as $pdOpportunity) {
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$record = [
'crmId' => $pdOpportunity->id,
'name' => $pdOpportunity->title,
'value' => $pdOpportunity->formatted_value,
'won' => $pdOpportunity->won_time !== null,
'closed' => $pdOpportunity->status !== 'open',
'stage' => [
'id' => $stage?->id_string ?? '',
'name' => $stage?->name ?? '',
],
'recordType' => [
'id' => $recordType?->id_string ?? '',
'name' => $recordType?->name ?? '',
],
];
if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
$pdActivities = null;
$filters = ['done' => 0];
switch ($objectType) {
case 'contact':
$pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();
break;
case 'account':
// Prioritize looking up activities on the deal (which should be linked on the account anyway).
if ($opportunityId) {
$pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();
}
// If no deal activity, fall back to the organization.
if ($pdActivities === null) {
$pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();
}
break;
}
if ($pdActivities === null) {
return [];
}
foreach ($pdActivities as $pdActivity) {
// Only import active, scheduled tasks in the future.
if ($pdActivity->active_flag) {
$due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');
$data[] = [
'crmId' => $pdActivity->id,
'subject' => $pdActivity->subject,
'due' => Carbon::parse($due)->toIso8601String(),
'type' => $pdActivity->type,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contact = null;
$account = null;
$params = [
'term' => $email,
'item_types' => 'person',
'fields' => 'email',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
$this->logger->info('[Pipedrive] Email match failed', [
'email' => $email,
'reason' => $exception->getMessage(),
]);
return null;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if (
! $contact instanceof Contact
&& ! $account instanceof Account
) {
return null;
}
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (count($pdOpportunities) > 0) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
// Check if the user is internal.
$teamMember = $this->team->users()->where('phone', $phone)->exists();
// Skip the attendee if internal.
if ($teamMember !== false) {
return null;
}
$params = [
'term' => $phone,
'item_types' => 'person,organization',
'fields' => 'phone',
];
$searchResult = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$searchResult = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Phone match failed', [
'phone' => $phone,
'reason' => $e->getMessage(),
]);
return null;
}
if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {
return null;
}
$contact = $this->syncContact($searchResult['items'][0]['item']['id']);
$account = $contact->account;
$countryCode = $this->getCountryCode($contact, $account);
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function getCountryCode($contact, $account): ?string
{
if ($contact && $contact->country_code) {
return $contact->country_code;
} elseif ($account && $account->country_code) {
return $account->country_code;
}
return null;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {
$contact = null;
$account = null;
$params = [
'term' => $name,
'item_types' => 'person',
'fields' => 'name',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Name match failed', [
'name' => $name,
'reason' => $e->getMessage(),
]);
return false;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if ($contact || $account) {
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
return false;
});
return is_array($result) ? $result : null;
}
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->type) {
case Activity::TYPE_CONFERENCE:
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildCallPayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"5","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"119","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"9","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Pipedrive;\n\nuse Carbon\\Carbon;\nuse Devio\\Pipedrive\\Exceptions\\ItemNotFoundException;\nuse Devio\\Pipedrive\\Exceptions\\PipedriveException;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\PipedriveInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Events\\Users\\SocialAccountDisconnected;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\SocialAccountTokenInvalidException;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Log;\nuse UnexpectedValueException;\n\nclass Service extends BaseService implements\n PipedriveInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string CALL_HEADER = 'Jiminny Summary';\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)\n {\n parent::__construct();\n\n $this->client = $client;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Pipedrive';\n }\n\n /**\n * @inheritdoc\n */\n public function setUser(User $user): void\n {\n try {\n parent::setUser($user);\n } catch (InvalidArgumentException $exception) {\n // In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.\n if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&\n $exception->getMessage() === 'Required option not passed: \"access_token\"') {\n // Something terrible happened to their token, they need to reconnect.\n $this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);\n\n event(new SocialAccountDisconnected($this->client->oauthAccount));\n }\n\n throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');\n }\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n switch ($fieldType) {\n case Field::TYPE_DATE:\n $value = $internal ? Carbon::parse($fieldValue) : $fieldValue;\n\n break;\n\n default:\n $value = $fieldValue;\n }\n\n return $value;\n }\n\n /**\n * Gets the valid fields for a given Object via the property APIs.\n *\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n switch ($crmObject) {\n case 'task':\n $properties = $this->client->getInstance()->activityFields();\n\n break;\n\n case 'account':\n $properties = $this->client->getInstance()->organizationFields();\n\n break;\n\n case 'contact':\n $properties = $this->client->getInstance()->personFields();\n\n break;\n\n case 'opportunity':\n $properties = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException();\n }\n\n $fields = [];\n\n try {\n $response = $properties->all();\n\n if ($response->isSuccess() === false) {\n throw new Exception($response->getContent(), $response->getStatusCode());\n }\n\n foreach ($response->getData() as $property) {\n $fields[] = ['label' => $property->name, 'name' => $property->key];\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n return;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n $field->description = null;\n $field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($crmField->field_type);\n $field->is_selectable = $crmField->active_flag;\n $field->save();\n }\n }\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'enum':\n case 'stage':\n case 'status':\n return Field::TYPE_PICKLIST;\n\n case 'varchar':\n return Field::TYPE_TEXT;\n\n case 'int':\n case 'double':\n return Field::TYPE_NUMBER;\n\n case 'text':\n return Field::TYPE_TEXTAREA;\n\n case 'monetary':\n return Field::TYPE_CURRENCY;\n\n case Field::TYPE_DATE:\n case Field::TYPE_TIME:\n case Field::TYPE_PHONE:\n return $fieldType;\n\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException('Invalid field type \"' . $field->object_type . '\" for field ' . $field->id . '.');\n }\n\n if ($field->crm_provider_id == 'stage_id') {\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n foreach ($pipelines as $pipeline) {\n $dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();\n foreach ($dealStages as $i => $dealStage) {\n $values = [\n 'value' => $dealStage->id,\n 'label' => $dealStage->name,\n 'sequence' => $i,\n ];\n\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $dealStage->id,\n ], $values);\n }\n }\n\n return $fieldValues;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n // Import all active values.\n if (property_exists($crmField, 'options')) {\n foreach ($crmField->options as $i => $option) {\n $values[] = [\n 'value' => $option->id,\n 'label' => $option->label,\n 'sequence' => $i,\n ];\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n *\n * @throws SocialAccountTokenInvalidException\n * @throws PipedriveException\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // We create a business process to contain the pipeline, and later store all stages against it.\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n\n foreach ($pipelines as $pipeline) {\n $businessProcess = $this->importPipelineData($pipeline);\n\n $stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);\n if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {\n $missingStage = $stage;\n }\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n // Pipedrive doesn't use leads.\n return 0;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n // Pipedrive doesn't use leads.\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdAccounts = $this->client->getInstance()->organizations()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdAccounts->getData() === null) {\n return 0;\n }\n\n foreach ($pdAccounts->getData() as $pdAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($pdAccount->id)) {\n $this->importAccount($pdAccount);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $hsAccount = $this->client->getInstance()->organizations()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importAccount($hsAccount->getData());\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData->country_code;\n if ($countryCode === null && $crmData->address_country) {\n $countryCode = $this->convertCountryNameToCode($crmData->address_country);\n }\n\n $name = $crmData->name;\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n /**\n * Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.\n * These are real samples from API results:\n * { ... owner_id: 23696001, ...}\n * OR\n * {\n * ...\n * owner_id: {\n * active_flag: false,\n * id: 12972717,\n * name: 'name here',\n * value: 12972717\n * }\n * }\n */\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Account::class,\n fileName: (string) $crmData->id,\n avatarText: $name,\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Account */\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {\n $this->importOpportunity($pdOpportunity);\n $syncCount++;\n }\n }\n\n $this->logger->info('[Pipedrive] Sync Opportunities completed', [\n 'team' => $this->team->getId(),\n 'syncCount' => $syncCount,\n ]);\n } catch (Exception $exception) {\n $this->logger->info('[Pipedrive] Failed to sync Opportunities ', [\n 'team' => $this->team->getId(),\n 'params' => $parameters,\n 'strategy' => $strategy,\n 'reason' => $exception->getMessage(),\n 'syncedBeforeFailure' => $syncCount,\n ]);\n }\n\n if ($syncCount > 1000) {\n $this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [\n 'team' => $this->team->getId(),\n 'total' => $syncCount,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = ['crm_id' => $crmId];\n\n try {\n $generator = $strategy->fetchOpportunities($parameters);\n $pdOpportunity = $generator->current();\n } catch (ItemNotFoundException | PipedriveException $e) {\n $this->logger->info('[Pipedrive] Failed to sync opportunity', [\n 'crm_id' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n return $this->importOpportunity($pdOpportunity);\n }\n\n /**\n * @inheritdoc\n */\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData->deleted) {\n return null;\n }\n\n if ($crmData->org_id) {\n $orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n $account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($orgId);\n\n if ($account === null) {\n // For some bizarre reason, the org_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);\n\n return null;\n }\n }\n } elseif ($crmData->person_id) {\n // Try to get the organization from the person.\n $personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;\n $contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();\n\n if ($contact === null || $contact->account_id === null) {\n $contact = $this->syncContact($personId);\n\n if ($contact === null) {\n // For some bizarre reason, the person_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);\n\n return null;\n }\n\n if ($contact->account_id === null) {\n $this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());\n\n return null;\n }\n }\n\n $account = $contact->account;\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $crmData->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $closeDate = null;\n if ($crmData->expected_close_date) {\n $closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');\n }\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n $data = [\n 'team_id' => $this->team?->getId(),\n 'account_id' => $account?->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->title, 0, 128),\n 'value' => $crmData->value,\n 'currency_code' => CurrencyFormatter::formatCode($crmData->currency),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData->close_time !== null,\n 'is_won' => $crmData->won_time !== null,\n 'stage_id' => $stage?->getId(),\n 'record_type_id' => $recordType?->getId(),\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdContacts = $this->client->getInstance()->persons()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdContacts->getData() === null) {\n return 0;\n }\n\n foreach ($pdContacts->getData() as $pdContact) {\n // Only sync if previously imported.\n if ($this->hasContact($pdContact->id)) {\n $this->importContact($pdContact);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $pdContact = $this->client->getInstance()->persons()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importContact($pdContact->getData());\n }\n\n private function importContact($crmData): Contact\n {\n $photoPath = null;\n $account = null;\n if ($crmData->org_id) {\n /**\n * Pipedrive API is inconsistent, it may return a string variable, or an object\n */\n $crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n\n $account = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmProviderId)\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmProviderId);\n $photoPath = $this->teamService->generateAvatar(\n $crmData->id,\n $crmData->name,\n );\n } else {\n $photoPath = $account->photo_path;\n }\n }\n\n if ($photoPath === null) {\n $photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Contact::class,\n fileName: (string) $crmData->id,\n avatarText: $crmData->name,\n );\n }\n\n $ownerId = $profile = null;\n if ($crmData->owner_id) {\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n }\n\n $parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);\n\n $mobileNumber = null;\n if (isset($crmData->phone[1])) {\n $mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);\n }\n\n $email = null;\n if (isset($crmData->email[0]->value)) {\n $email = mb_strimwidth($crmData->email[0]->value, 0, 191);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->name ?? '', 0, 100),\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobileNumber ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData->job_title ?? null,\n 'photo_path' => $photoPath,\n 'remotely_created_at' => Carbon::parse($crmData->add_time),\n ];\n\n /** @var Contact */\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n // Not applicable.\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?\\Jiminny\\Models\\Crm\\Profile\n {\n // Not needed yet.\n return null;\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);\n\n /*\n // If they have changed, raise a notification to the owner.\n $team->owner->notify(\n new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)\n );\n */\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (Exception $exception) {\n Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {\n $data = [];\n $params = [\n 'term' => $name,\n 'limit' => $count,\n 'start' => $offset,\n 'item_types' => 'person,organization',\n ];\n\n $objects = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $objects = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n if (empty($objects['items'])) {\n return [];\n }\n\n // Build mapped list.\n foreach ($objects['items'] as $object) {\n $object = $object['item'];\n\n // We only support these object types today.\n if (\\in_array($object['type'], ['person', 'organization']) === false) {\n continue;\n }\n\n $objectType = $object['type'] === 'person' ? 'contact' : 'account';\n $record = [\n 'crmId' => $object['id'],\n 'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),\n 'name' => $object['name'],\n 'industry' => null,\n 'title' => null,\n 'prospectType' => $objectType,\n 'phoneNumbers' => [],\n ];\n\n if (isset($object['organization']['name'])) {\n $record['organization'] = $object['organization']['name'];\n }\n\n if (isset($object['phones'][0])) {\n $parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);\n\n // Add phone number to record.\n if (empty($parsedNumber['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national(null, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n }\n\n $data[] = $record;\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'only_primary_association' => 1,\n 'status' => 'open',\n 'sort' => 'update_time DESC',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = 'add_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = 'add_time ASC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n $params['status'] = 'all_not_deleted';\n }\n\n $pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n if ($pdOpportunities === null) {\n return [];\n }\n\n foreach ($pdOpportunities as $pdOpportunity) {\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $record = [\n 'crmId' => $pdOpportunity->id,\n 'name' => $pdOpportunity->title,\n 'value' => $pdOpportunity->formatted_value,\n 'won' => $pdOpportunity->won_time !== null,\n 'closed' => $pdOpportunity->status !== 'open',\n 'stage' => [\n 'id' => $stage?->id_string ?? '',\n 'name' => $stage?->name ?? '',\n ],\n 'recordType' => [\n 'id' => $recordType?->id_string ?? '',\n 'name' => $recordType?->name ?? '',\n ],\n ];\n\n if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n $pdActivities = null;\n $filters = ['done' => 0];\n switch ($objectType) {\n case 'contact':\n $pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();\n\n break;\n case 'account':\n // Prioritize looking up activities on the deal (which should be linked on the account anyway).\n if ($opportunityId) {\n $pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();\n }\n\n // If no deal activity, fall back to the organization.\n if ($pdActivities === null) {\n $pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();\n }\n\n break;\n }\n\n if ($pdActivities === null) {\n return [];\n }\n\n foreach ($pdActivities as $pdActivity) {\n // Only import active, scheduled tasks in the future.\n if ($pdActivity->active_flag) {\n $due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');\n $data[] = [\n 'crmId' => $pdActivity->id,\n 'subject' => $pdActivity->subject,\n 'due' => Carbon::parse($due)->toIso8601String(),\n 'type' => $pdActivity->type,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $email,\n 'item_types' => 'person',\n 'fields' => 'email',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n $this->logger->info('[Pipedrive] Email match failed', [\n 'email' => $email,\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if (\n ! $contact instanceof Contact\n && ! $account instanceof Account\n ) {\n return null;\n }\n\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n if (count($pdOpportunities) > 0) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember !== false) {\n return null;\n }\n\n $params = [\n 'term' => $phone,\n 'item_types' => 'person,organization',\n 'fields' => 'phone',\n ];\n\n $searchResult = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $searchResult = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {\n return null;\n }\n\n $contact = $this->syncContact($searchResult['items'][0]['item']['id']);\n $account = $contact->account;\n\n $countryCode = $this->getCountryCode($contact, $account);\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function getCountryCode($contact, $account): ?string\n {\n if ($contact && $contact->country_code) {\n return $contact->country_code;\n } elseif ($account && $account->country_code) {\n return $account->country_code;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $name,\n 'item_types' => 'person',\n 'fields' => 'name',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Name match failed', [\n 'name' => $name,\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if ($contact || $account) {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n return false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'person_id' => $activity->hasContact() ? $activity->getContact()->getCrmProviderId() : null,\n 'org_id' => $activity->hasAccount() ? $activity->getAccount()->getCrmProviderId() : null,\n 'deal_id' => $activity->hasOpportunity() ? $activity->getOpportunity()->getCrmProviderId() : null,\n ];\n }\n\n private function buildCallPayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->scheduled_start_time->format('H:i'),\n 'due_date' => $activity->scheduled_start_time->toDateString(),\n 'duration' => gmdate('H:i', $activity->duration),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->fetchCustomFieldData($activity, Field::OBJECT_TASK)\n + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->created_at->format('H:i'),\n 'due_date' => $activity->created_at->toDateString(),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function upsertActivity(Activity $activity, array $data): Activity\n {\n // The activity should be logged under an existing activity.\n if ($activity->hasCrmProviderId()) {\n $existingActivity = $this->client->getActivity($activity->getCrmProviderId());\n\n if ($existingActivity && $existingData = $existingActivity->getData()) {\n $existingData = (array) $existingData;\n $data = $this->updateDescription($existingData, $data);\n $data = $this->updateProspectData($existingData, $data);\n\n // Just update the existing engagement with any fresh details.\n $this->client->updateActivity($activity->getCrmProviderId(), $data);\n }\n } else {\n $pdActivity = $this->client->createActivity($data);\n\n $activity->crm_provider_id = $pdActivity->getData()->id;\n $activity->save();\n }\n\n return $activity;\n }\n\n private function updateDescription(array $crmActivityData, array $payloadData): array\n {\n $crmActivityNote = $crmActivityData['note'] ?? null;\n\n if (! empty($crmActivityNote)) {\n if (! str_contains($crmActivityNote, self::CALL_HEADER)) {\n $payloadData['note'] = $crmActivityNote . \"\\n\\n\" . $payloadData['note'];\n } else {\n $payloadData['note'] = $crmActivityNote;\n }\n }\n\n return $payloadData;\n }\n\n private function updateProspectData($crmActivityData, array $data): array\n {\n $changedData = [];\n if ($crmActivityData['person_id'] && ! isset($data['person_id'])) {\n $changedData['person_id'] = $crmActivityData['person_id'];\n $data['person_id'] = $crmActivityData['person_id'];\n $data['org_id'] = null;\n $data['deal_id'] = null;\n } elseif (isset($data['person_id']) && $data['person_id'] != $crmActivityData['person_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in person_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['person_id'],\n 'crm_activity_data' => $crmActivityData['person_id'],\n ]);\n }\n\n if ($crmActivityData['org_id'] && ! isset($data['org_id'])) {\n $changedData['org_id'] = $crmActivityData['org_id'];\n $data['org_id'] = $crmActivityData['org_id'];\n $data['deal_id'] = null;\n } elseif (isset($data['org_id']) && $data['org_id'] != $crmActivityData['org_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in org_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['org_id'],\n 'crm_activity_data' => $crmActivityData['org_id'],\n ]);\n }\n\n if ($crmActivityData['deal_id'] && ! isset($data['deal_id'])) {\n $changedData['deal_id'] = $crmActivityData['deal_id'];\n $data['deal_id'] = $crmActivityData['deal_id'];\n } elseif (isset($data['deal_id']) && $data['deal_id'] != $crmActivityData['deal_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in deal_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['deal_id'],\n 'crm_activity_data' => $crmActivityData['deal_id'],\n ]);\n }\n\n if (! empty($changedData)) {\n $this->logger->info('[Pipedrive] Updated activity associations', $changedData);\n }\n\n return $data;\n }\n\n private function generateActivityTitle(Activity $activity): string\n {\n if ($activity->hasTitle()) {\n $title = $activity->title;\n } elseif ($activity->playbook_category_id) {\n $title = $activity->category->name;\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n self::CALL_HEADER\n );\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->hasTitle()) {\n // Insert the activity type since there is no native field.\n $description .= sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n $activity->category->name,\n );\n }\n\n if ($activity->isTypeSoftPhone()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">Review in Jiminny</a>'\n . ' ▶️'\n . '</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->type === Activity::TYPE_CONFERENCE) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity type field.\n if (empty($fields['type'])) {\n return null;\n }\n\n if (empty($fields['subject'])) {\n // We need to convert the name correctly.\n $playbook = $this->getPlaybook($activity->getUser());\n $type = $playbook->activityField->values()->where('value', $fields['type'])->first();\n $subject = ($type->label ?? $fields['type']) . ' with ' . $activity->prospect_name;\n } else {\n $subject = $fields['subject'];\n }\n\n $data = [\n 'done' => 0,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_date' => $fields['due_date'] ?? date('Y-m-d'),\n 'due_time' => $fields['due_time'] ?? null,\n 'subject' => $subject,\n 'type' => $fields['type'],\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->activities()->add($data);\n\n // We don't actually create a corresponding activity object on our side yet.\n return $pdActivity->getData()->id;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, self::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'content' => $transcripts,\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->notes()->add($data);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $pdActivity->getData()->id;\n $transcription->save();\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->convertObjectTypeToResource($objectType)->update($objectId, $data);\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n $record = $this->convertObjectTypeToResource($objectType)->find($objectId)->getData();\n\n // We could map the fields requested here before returning.\n return $record ? (array) $record : [];\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case parent::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals();\n\n case parent::OBJECT_CONTACT:\n return $this->client->getInstance()->persons();\n\n case parent::OBJECT_ACCOUNT:\n return $this->client->getInstance()->organizations();\n\n case parent::OBJECT_TASK:\n return $this->client->getInstance()->activities();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \".$objectType.\"');\n }\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, [\n 'stage_id' => $stage->crm_provider_id,\n ]);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->field->crm_provider_id => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n switch ($objectType) {\n case 'account':\n $url = $this->config->crm_base_url . '/organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $this->config->crm_base_url . '/person/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $this->config->crm_base_url . '/deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Pipedrive UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n public function importPipeline(int $pipelineId): ?BusinessProcess\n {\n try {\n $pipeline = $this->client->getInstance()->pipelines()->find($pipelineId)->getData();\n } catch (ItemNotFoundException $exception) {\n return null;\n }\n\n if ($pipeline === null) {\n return null;\n }\n\n return $this->importPipelineData($pipeline);\n }\n\n private function importPipelineData(mixed $pipeline): BusinessProcess\n {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $pipeline->active,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'is_selectable' => $pipeline->active,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n return $businessProcess;\n }\n\n private function importStagesForBusinessProcess(BusinessProcess $businessProcess, ?string $missingId): ?Stage\n {\n $missingStage = null;\n $stages = [];\n $dealStages = $this->client->getInstance()\n ->stages()\n ->all(['pipeline_id' => (int) $businessProcess->crm_provider_id])\n ->getData();\n\n foreach ($dealStages as $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->importStage($dealStage);\n\n if ($missingId !== null && $stage->crm_provider_id == $missingId) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n\n return $missingStage;\n }\n\n private function importStage(mixed $dealStage): Stage\n {\n return $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage->name, 0, 50),\n 'label' => mb_strimwidth($dealStage->name, 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $dealStage->order_nr,\n 'is_selectable' => $dealStage->active_flag,\n 'probability' => $dealStage->deal_probability,\n ]);\n }\n\n private function getBusinessProcesses(string $pipelineId): ?BusinessProcess\n {\n return $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $pipelineId)\n ->first();\n }\n\n private function getStage(?BusinessProcess $businessProcess, string $stageId): ?Stage\n {\n return $businessProcess\n ?->stages()\n ->where('crm_provider_id', $stageId)\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if (! is_numeric($crmProviderId)) {\n $this->logger->warning('[Pipedrive] Invalid activity ID format', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n $activity = $this->client->getActivity($crmProviderId);\n\n return ($activity->active_flag ?? false) === true;\n } catch (HttpNotFoundException) {\n // Activity not found in CRM - this is expected and permanent\n $this->logger->info('[Pipedrive] Activity not found during verification', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Pipedrive;\n\nuse Carbon\\Carbon;\nuse Devio\\Pipedrive\\Exceptions\\ItemNotFoundException;\nuse Devio\\Pipedrive\\Exceptions\\PipedriveException;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\PipedriveInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Events\\Users\\SocialAccountDisconnected;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\SocialAccountTokenInvalidException;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Log;\nuse UnexpectedValueException;\n\nclass Service extends BaseService implements\n PipedriveInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string CALL_HEADER = 'Jiminny Summary';\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)\n {\n parent::__construct();\n\n $this->client = $client;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Pipedrive';\n }\n\n /**\n * @inheritdoc\n */\n public function setUser(User $user): void\n {\n try {\n parent::setUser($user);\n } catch (InvalidArgumentException $exception) {\n // In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.\n if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&\n $exception->getMessage() === 'Required option not passed: \"access_token\"') {\n // Something terrible happened to their token, they need to reconnect.\n $this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);\n\n event(new SocialAccountDisconnected($this->client->oauthAccount));\n }\n\n throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');\n }\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n switch ($fieldType) {\n case Field::TYPE_DATE:\n $value = $internal ? Carbon::parse($fieldValue) : $fieldValue;\n\n break;\n\n default:\n $value = $fieldValue;\n }\n\n return $value;\n }\n\n /**\n * Gets the valid fields for a given Object via the property APIs.\n *\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n switch ($crmObject) {\n case 'task':\n $properties = $this->client->getInstance()->activityFields();\n\n break;\n\n case 'account':\n $properties = $this->client->getInstance()->organizationFields();\n\n break;\n\n case 'contact':\n $properties = $this->client->getInstance()->personFields();\n\n break;\n\n case 'opportunity':\n $properties = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException();\n }\n\n $fields = [];\n\n try {\n $response = $properties->all();\n\n if ($response->isSuccess() === false) {\n throw new Exception($response->getContent(), $response->getStatusCode());\n }\n\n foreach ($response->getData() as $property) {\n $fields[] = ['label' => $property->name, 'name' => $property->key];\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n return;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n $field->description = null;\n $field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($crmField->field_type);\n $field->is_selectable = $crmField->active_flag;\n $field->save();\n }\n }\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'enum':\n case 'stage':\n case 'status':\n return Field::TYPE_PICKLIST;\n\n case 'varchar':\n return Field::TYPE_TEXT;\n\n case 'int':\n case 'double':\n return Field::TYPE_NUMBER;\n\n case 'text':\n return Field::TYPE_TEXTAREA;\n\n case 'monetary':\n return Field::TYPE_CURRENCY;\n\n case Field::TYPE_DATE:\n case Field::TYPE_TIME:\n case Field::TYPE_PHONE:\n return $fieldType;\n\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException('Invalid field type \"' . $field->object_type . '\" for field ' . $field->id . '.');\n }\n\n if ($field->crm_provider_id == 'stage_id') {\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n foreach ($pipelines as $pipeline) {\n $dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();\n foreach ($dealStages as $i => $dealStage) {\n $values = [\n 'value' => $dealStage->id,\n 'label' => $dealStage->name,\n 'sequence' => $i,\n ];\n\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $dealStage->id,\n ], $values);\n }\n }\n\n return $fieldValues;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n // Import all active values.\n if (property_exists($crmField, 'options')) {\n foreach ($crmField->options as $i => $option) {\n $values[] = [\n 'value' => $option->id,\n 'label' => $option->label,\n 'sequence' => $i,\n ];\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n *\n * @throws SocialAccountTokenInvalidException\n * @throws PipedriveException\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // We create a business process to contain the pipeline, and later store all stages against it.\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n\n foreach ($pipelines as $pipeline) {\n $businessProcess = $this->importPipelineData($pipeline);\n\n $stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);\n if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {\n $missingStage = $stage;\n }\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n // Pipedrive doesn't use leads.\n return 0;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n // Pipedrive doesn't use leads.\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdAccounts = $this->client->getInstance()->organizations()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdAccounts->getData() === null) {\n return 0;\n }\n\n foreach ($pdAccounts->getData() as $pdAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($pdAccount->id)) {\n $this->importAccount($pdAccount);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $hsAccount = $this->client->getInstance()->organizations()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importAccount($hsAccount->getData());\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData->country_code;\n if ($countryCode === null && $crmData->address_country) {\n $countryCode = $this->convertCountryNameToCode($crmData->address_country);\n }\n\n $name = $crmData->name;\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n /**\n * Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.\n * These are real samples from API results:\n * { ... owner_id: 23696001, ...}\n * OR\n * {\n * ...\n * owner_id: {\n * active_flag: false,\n * id: 12972717,\n * name: 'name here',\n * value: 12972717\n * }\n * }\n */\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Account::class,\n fileName: (string) $crmData->id,\n avatarText: $name,\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Account */\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {\n $this->importOpportunity($pdOpportunity);\n $syncCount++;\n }\n }\n\n $this->logger->info('[Pipedrive] Sync Opportunities completed', [\n 'team' => $this->team->getId(),\n 'syncCount' => $syncCount,\n ]);\n } catch (Exception $exception) {\n $this->logger->info('[Pipedrive] Failed to sync Opportunities ', [\n 'team' => $this->team->getId(),\n 'params' => $parameters,\n 'strategy' => $strategy,\n 'reason' => $exception->getMessage(),\n 'syncedBeforeFailure' => $syncCount,\n ]);\n }\n\n if ($syncCount > 1000) {\n $this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [\n 'team' => $this->team->getId(),\n 'total' => $syncCount,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = ['crm_id' => $crmId];\n\n try {\n $generator = $strategy->fetchOpportunities($parameters);\n $pdOpportunity = $generator->current();\n } catch (ItemNotFoundException | PipedriveException $e) {\n $this->logger->info('[Pipedrive] Failed to sync opportunity', [\n 'crm_id' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n return $this->importOpportunity($pdOpportunity);\n }\n\n /**\n * @inheritdoc\n */\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData->deleted) {\n return null;\n }\n\n if ($crmData->org_id) {\n $orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n $account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($orgId);\n\n if ($account === null) {\n // For some bizarre reason, the org_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);\n\n return null;\n }\n }\n } elseif ($crmData->person_id) {\n // Try to get the organization from the person.\n $personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;\n $contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();\n\n if ($contact === null || $contact->account_id === null) {\n $contact = $this->syncContact($personId);\n\n if ($contact === null) {\n // For some bizarre reason, the person_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);\n\n return null;\n }\n\n if ($contact->account_id === null) {\n $this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());\n\n return null;\n }\n }\n\n $account = $contact->account;\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $crmData->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $closeDate = null;\n if ($crmData->expected_close_date) {\n $closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');\n }\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n $data = [\n 'team_id' => $this->team?->getId(),\n 'account_id' => $account?->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->title, 0, 128),\n 'value' => $crmData->value,\n 'currency_code' => CurrencyFormatter::formatCode($crmData->currency),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData->close_time !== null,\n 'is_won' => $crmData->won_time !== null,\n 'stage_id' => $stage?->getId(),\n 'record_type_id' => $recordType?->getId(),\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdContacts = $this->client->getInstance()->persons()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdContacts->getData() === null) {\n return 0;\n }\n\n foreach ($pdContacts->getData() as $pdContact) {\n // Only sync if previously imported.\n if ($this->hasContact($pdContact->id)) {\n $this->importContact($pdContact);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $pdContact = $this->client->getInstance()->persons()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importContact($pdContact->getData());\n }\n\n private function importContact($crmData): Contact\n {\n $photoPath = null;\n $account = null;\n if ($crmData->org_id) {\n /**\n * Pipedrive API is inconsistent, it may return a string variable, or an object\n */\n $crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n\n $account = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmProviderId)\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmProviderId);\n $photoPath = $this->teamService->generateAvatar(\n $crmData->id,\n $crmData->name,\n );\n } else {\n $photoPath = $account->photo_path;\n }\n }\n\n if ($photoPath === null) {\n $photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Contact::class,\n fileName: (string) $crmData->id,\n avatarText: $crmData->name,\n );\n }\n\n $ownerId = $profile = null;\n if ($crmData->owner_id) {\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n }\n\n $parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);\n\n $mobileNumber = null;\n if (isset($crmData->phone[1])) {\n $mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);\n }\n\n $email = null;\n if (isset($crmData->email[0]->value)) {\n $email = mb_strimwidth($crmData->email[0]->value, 0, 191);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->name ?? '', 0, 100),\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobileNumber ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData->job_title ?? null,\n 'photo_path' => $photoPath,\n 'remotely_created_at' => Carbon::parse($crmData->add_time),\n ];\n\n /** @var Contact */\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n // Not applicable.\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?\\Jiminny\\Models\\Crm\\Profile\n {\n // Not needed yet.\n return null;\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);\n\n /*\n // If they have changed, raise a notification to the owner.\n $team->owner->notify(\n new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)\n );\n */\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (Exception $exception) {\n Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {\n $data = [];\n $params = [\n 'term' => $name,\n 'limit' => $count,\n 'start' => $offset,\n 'item_types' => 'person,organization',\n ];\n\n $objects = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $objects = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n if (empty($objects['items'])) {\n return [];\n }\n\n // Build mapped list.\n foreach ($objects['items'] as $object) {\n $object = $object['item'];\n\n // We only support these object types today.\n if (\\in_array($object['type'], ['person', 'organization']) === false) {\n continue;\n }\n\n $objectType = $object['type'] === 'person' ? 'contact' : 'account';\n $record = [\n 'crmId' => $object['id'],\n 'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),\n 'name' => $object['name'],\n 'industry' => null,\n 'title' => null,\n 'prospectType' => $objectType,\n 'phoneNumbers' => [],\n ];\n\n if (isset($object['organization']['name'])) {\n $record['organization'] = $object['organization']['name'];\n }\n\n if (isset($object['phones'][0])) {\n $parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);\n\n // Add phone number to record.\n if (empty($parsedNumber['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national(null, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n }\n\n $data[] = $record;\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'only_primary_association' => 1,\n 'status' => 'open',\n 'sort' => 'update_time DESC',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = 'add_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = 'add_time ASC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n $params['status'] = 'all_not_deleted';\n }\n\n $pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n if ($pdOpportunities === null) {\n return [];\n }\n\n foreach ($pdOpportunities as $pdOpportunity) {\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $record = [\n 'crmId' => $pdOpportunity->id,\n 'name' => $pdOpportunity->title,\n 'value' => $pdOpportunity->formatted_value,\n 'won' => $pdOpportunity->won_time !== null,\n 'closed' => $pdOpportunity->status !== 'open',\n 'stage' => [\n 'id' => $stage?->id_string ?? '',\n 'name' => $stage?->name ?? '',\n ],\n 'recordType' => [\n 'id' => $recordType?->id_string ?? '',\n 'name' => $recordType?->name ?? '',\n ],\n ];\n\n if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n $pdActivities = null;\n $filters = ['done' => 0];\n switch ($objectType) {\n case 'contact':\n $pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();\n\n break;\n case 'account':\n // Prioritize looking up activities on the deal (which should be linked on the account anyway).\n if ($opportunityId) {\n $pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();\n }\n\n // If no deal activity, fall back to the organization.\n if ($pdActivities === null) {\n $pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();\n }\n\n break;\n }\n\n if ($pdActivities === null) {\n return [];\n }\n\n foreach ($pdActivities as $pdActivity) {\n // Only import active, scheduled tasks in the future.\n if ($pdActivity->active_flag) {\n $due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');\n $data[] = [\n 'crmId' => $pdActivity->id,\n 'subject' => $pdActivity->subject,\n 'due' => Carbon::parse($due)->toIso8601String(),\n 'type' => $pdActivity->type,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $email,\n 'item_types' => 'person',\n 'fields' => 'email',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n $this->logger->info('[Pipedrive] Email match failed', [\n 'email' => $email,\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if (\n ! $contact instanceof Contact\n && ! $account instanceof Account\n ) {\n return null;\n }\n\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n if (count($pdOpportunities) > 0) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember !== false) {\n return null;\n }\n\n $params = [\n 'term' => $phone,\n 'item_types' => 'person,organization',\n 'fields' => 'phone',\n ];\n\n $searchResult = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $searchResult = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {\n return null;\n }\n\n $contact = $this->syncContact($searchResult['items'][0]['item']['id']);\n $account = $contact->account;\n\n $countryCode = $this->getCountryCode($contact, $account);\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function getCountryCode($contact, $account): ?string\n {\n if ($contact && $contact->country_code) {\n return $contact->country_code;\n } elseif ($account && $account->country_code) {\n return $account->country_code;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $name,\n 'item_types' => 'person',\n 'fields' => 'name',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Name match failed', [\n 'name' => $name,\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if ($contact || $account) {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n return false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'person_id' => $activity->hasContact() ? $activity->getContact()->getCrmProviderId() : null,\n 'org_id' => $activity->hasAccount() ? $activity->getAccount()->getCrmProviderId() : null,\n 'deal_id' => $activity->hasOpportunity() ? $activity->getOpportunity()->getCrmProviderId() : null,\n ];\n }\n\n private function buildCallPayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->scheduled_start_time->format('H:i'),\n 'due_date' => $activity->scheduled_start_time->toDateString(),\n 'duration' => gmdate('H:i', $activity->duration),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->fetchCustomFieldData($activity, Field::OBJECT_TASK)\n + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->created_at->format('H:i'),\n 'due_date' => $activity->created_at->toDateString(),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function upsertActivity(Activity $activity, array $data): Activity\n {\n // The activity should be logged under an existing activity.\n if ($activity->hasCrmProviderId()) {\n $existingActivity = $this->client->getActivity($activity->getCrmProviderId());\n\n if ($existingActivity && $existingData = $existingActivity->getData()) {\n $existingData = (array) $existingData;\n $data = $this->updateDescription($existingData, $data);\n $data = $this->updateProspectData($existingData, $data);\n\n // Just update the existing engagement with any fresh details.\n $this->client->updateActivity($activity->getCrmProviderId(), $data);\n }\n } else {\n $pdActivity = $this->client->createActivity($data);\n\n $activity->crm_provider_id = $pdActivity->getData()->id;\n $activity->save();\n }\n\n return $activity;\n }\n\n private function updateDescription(array $crmActivityData, array $payloadData): array\n {\n $crmActivityNote = $crmActivityData['note'] ?? null;\n\n if (! empty($crmActivityNote)) {\n if (! str_contains($crmActivityNote, self::CALL_HEADER)) {\n $payloadData['note'] = $crmActivityNote . \"\\n\\n\" . $payloadData['note'];\n } else {\n $payloadData['note'] = $crmActivityNote;\n }\n }\n\n return $payloadData;\n }\n\n private function updateProspectData($crmActivityData, array $data): array\n {\n $changedData = [];\n if ($crmActivityData['person_id'] && ! isset($data['person_id'])) {\n $changedData['person_id'] = $crmActivityData['person_id'];\n $data['person_id'] = $crmActivityData['person_id'];\n $data['org_id'] = null;\n $data['deal_id'] = null;\n } elseif (isset($data['person_id']) && $data['person_id'] != $crmActivityData['person_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in person_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['person_id'],\n 'crm_activity_data' => $crmActivityData['person_id'],\n ]);\n }\n\n if ($crmActivityData['org_id'] && ! isset($data['org_id'])) {\n $changedData['org_id'] = $crmActivityData['org_id'];\n $data['org_id'] = $crmActivityData['org_id'];\n $data['deal_id'] = null;\n } elseif (isset($data['org_id']) && $data['org_id'] != $crmActivityData['org_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in org_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['org_id'],\n 'crm_activity_data' => $crmActivityData['org_id'],\n ]);\n }\n\n if ($crmActivityData['deal_id'] && ! isset($data['deal_id'])) {\n $changedData['deal_id'] = $crmActivityData['deal_id'];\n $data['deal_id'] = $crmActivityData['deal_id'];\n } elseif (isset($data['deal_id']) && $data['deal_id'] != $crmActivityData['deal_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in deal_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['deal_id'],\n 'crm_activity_data' => $crmActivityData['deal_id'],\n ]);\n }\n\n if (! empty($changedData)) {\n $this->logger->info('[Pipedrive] Updated activity associations', $changedData);\n }\n\n return $data;\n }\n\n private function generateActivityTitle(Activity $activity): string\n {\n if ($activity->hasTitle()) {\n $title = $activity->title;\n } elseif ($activity->playbook_category_id) {\n $title = $activity->category->name;\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n self::CALL_HEADER\n );\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->hasTitle()) {\n // Insert the activity type since there is no native field.\n $description .= sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n $activity->category->name,\n );\n }\n\n if ($activity->isTypeSoftPhone()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">Review in Jiminny</a>'\n . ' ▶️'\n . '</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->type === Activity::TYPE_CONFERENCE) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity type field.\n if (empty($fields['type'])) {\n return null;\n }\n\n if (empty($fields['subject'])) {\n // We need to convert the name correctly.\n $playbook = $this->getPlaybook($activity->getUser());\n $type = $playbook->activityField->values()->where('value', $fields['type'])->first();\n $subject = ($type->label ?? $fields['type']) . ' with ' . $activity->prospect_name;\n } else {\n $subject = $fields['subject'];\n }\n\n $data = [\n 'done' => 0,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_date' => $fields['due_date'] ?? date('Y-m-d'),\n 'due_time' => $fields['due_time'] ?? null,\n 'subject' => $subject,\n 'type' => $fields['type'],\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->activities()->add($data);\n\n // We don't actually create a corresponding activity object on our side yet.\n return $pdActivity->getData()->id;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, self::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'content' => $transcripts,\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->notes()->add($data);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $pdActivity->getData()->id;\n $transcription->save();\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->convertObjectTypeToResource($objectType)->update($objectId, $data);\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n $record = $this->convertObjectTypeToResource($objectType)->find($objectId)->getData();\n\n // We could map the fields requested here before returning.\n return $record ? (array) $record : [];\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case parent::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals();\n\n case parent::OBJECT_CONTACT:\n return $this->client->getInstance()->persons();\n\n case parent::OBJECT_ACCOUNT:\n return $this->client->getInstance()->organizations();\n\n case parent::OBJECT_TASK:\n return $this->client->getInstance()->activities();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \".$objectType.\"');\n }\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, [\n 'stage_id' => $stage->crm_provider_id,\n ]);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->field->crm_provider_id => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n switch ($objectType) {\n case 'account':\n $url = $this->config->crm_base_url . '/organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $this->config->crm_base_url . '/person/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $this->config->crm_base_url . '/deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Pipedrive UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n public function importPipeline(int $pipelineId): ?BusinessProcess\n {\n try {\n $pipeline = $this->client->getInstance()->pipelines()->find($pipelineId)->getData();\n } catch (ItemNotFoundException $exception) {\n return null;\n }\n\n if ($pipeline === null) {\n return null;\n }\n\n return $this->importPipelineData($pipeline);\n }\n\n private function importPipelineData(mixed $pipeline): BusinessProcess\n {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $pipeline->active,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'is_selectable' => $pipeline->active,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n return $businessProcess;\n }\n\n private function importStagesForBusinessProcess(BusinessProcess $businessProcess, ?string $missingId): ?Stage\n {\n $missingStage = null;\n $stages = [];\n $dealStages = $this->client->getInstance()\n ->stages()\n ->all(['pipeline_id' => (int) $businessProcess->crm_provider_id])\n ->getData();\n\n foreach ($dealStages as $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->importStage($dealStage);\n\n if ($missingId !== null && $stage->crm_provider_id == $missingId) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n\n return $missingStage;\n }\n\n private function importStage(mixed $dealStage): Stage\n {\n return $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage->name, 0, 50),\n 'label' => mb_strimwidth($dealStage->name, 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $dealStage->order_nr,\n 'is_selectable' => $dealStage->active_flag,\n 'probability' => $dealStage->deal_probability,\n ]);\n }\n\n private function getBusinessProcesses(string $pipelineId): ?BusinessProcess\n {\n return $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $pipelineId)\n ->first();\n }\n\n private function getStage(?BusinessProcess $businessProcess, string $stageId): ?Stage\n {\n return $businessProcess\n ?->stages()\n ->where('crm_provider_id', $stageId)\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if (! is_numeric($crmProviderId)) {\n $this->logger->warning('[Pipedrive] Invalid activity ID format', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n $activity = $this->client->getActivity($crmProviderId);\n\n return ($activity->active_flag ?? false) === true;\n } catch (HttpNotFoundException) {\n // Activity not found in CRM - this is expected and permanent\n $this->logger->info('[Pipedrive] Activity not found during verification', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false}]...
|
3865544371963712397
|
-7980155751442543530
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3
9
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Pipedrive;
use Carbon\Carbon;
use Devio\Pipedrive\Exceptions\ItemNotFoundException;
use Devio\Pipedrive\Exceptions\PipedriveException;
use Exception;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\PipedriveInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Events\Users\SocialAccountDisconnected;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\SocialAccountTokenInvalidException;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Log;
use UnexpectedValueException;
class Service extends BaseService implements
PipedriveInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string CALL_HEADER = 'Jiminny Summary';
/**
* @var ClientInterface|Client
*/
protected $client;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)
{
parent::__construct();
$this->client = $client;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Pipedrive';
}
/**
* @inheritdoc
*/
public function setUser(User $user): void
{
try {
parent::setUser($user);
} catch (InvalidArgumentException $exception) {
// In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.
if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&
$exception->getMessage() === 'Required option not passed: "access_token"') {
// Something terrible happened to their token, they need to reconnect.
$this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);
event(new SocialAccountDisconnected($this->client->oauthAccount));
}
throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');
}
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
switch ($fieldType) {
case Field::TYPE_DATE:
$value = $internal ? Carbon::parse($fieldValue) : $fieldValue;
break;
default:
$value = $fieldValue;
}
return $value;
}
/**
* Gets the valid fields for a given Object via the property APIs.
*
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
switch ($crmObject) {
case 'task':
$properties = $this->client->getInstance()->activityFields();
break;
case 'account':
$properties = $this->client->getInstance()->organizationFields();
break;
case 'contact':
$properties = $this->client->getInstance()->personFields();
break;
case 'opportunity':
$properties = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException();
}
$fields = [];
try {
$response = $properties->all();
if ($response->isSuccess() === false) {
throw new Exception($response->getContent(), $response->getStatusCode());
}
foreach ($response->getData() as $property) {
$fields[] = ['label' => $property->name, 'name' => $property->key];
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
return;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
$field->description = null;
$field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($crmField->field_type);
$field->is_selectable = $crmField->active_flag;
$field->save();
}
}
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'enum':
case 'stage':
case 'status':
return Field::TYPE_PICKLIST;
case 'varchar':
return Field::TYPE_TEXT;
case 'int':
case 'double':
return Field::TYPE_NUMBER;
case 'text':
return Field::TYPE_TEXTAREA;
case 'monetary':
return Field::TYPE_CURRENCY;
case Field::TYPE_DATE:
case Field::TYPE_TIME:
case Field::TYPE_PHONE:
return $fieldType;
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException('Invalid field type "' . $field->object_type . '" for field ' . $field->id . '.');
}
if ($field->crm_provider_id == 'stage_id') {
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();
foreach ($dealStages as $i => $dealStage) {
$values = [
'value' => $dealStage->id,
'label' => $dealStage->name,
'sequence' => $i,
];
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $dealStage->id,
], $values);
}
}
return $fieldValues;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
// Import all active values.
if (property_exists($crmField, 'options')) {
foreach ($crmField->options as $i => $option) {
$values[] = [
'value' => $option->id,
'label' => $option->label,
'sequence' => $i,
];
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
return $fieldValues;
}
/**
* @inheritdoc
*
* @throws SocialAccountTokenInvalidException
* @throws PipedriveException
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// We create a business process to contain the pipeline, and later store all stages against it.
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$businessProcess = $this->importPipelineData($pipeline);
$stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);
if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {
$missingStage = $stage;
}
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
// Pipedrive doesn't use leads.
return 0;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
// Pipedrive doesn't use leads.
return null;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdAccounts = $this->client->getInstance()->organizations()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdAccounts->getData() === null) {
return 0;
}
foreach ($pdAccounts->getData() as $pdAccount) {
// Only sync if previously imported.
if ($this->hasAccount($pdAccount->id)) {
$this->importAccount($pdAccount);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
try {
$hsAccount = $this->client->getInstance()->organizations()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);
}
return $this->importAccount($hsAccount->getData());
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = $crmData->country_code;
if ($countryCode === null && $crmData->address_country) {
$countryCode = $this->convertCountryNameToCode($crmData->address_country);
}
$name = $crmData->name;
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
/**
* Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.
* These are real samples from API results:
* { ... owner_id: 23696001, ...}
* OR
* {
* ...
* owner_id: {
* active_flag: false,
* id: 12972717,
* name: 'name here',
* value: 12972717
* }
* }
*/
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Account::class,
fileName: (string) $crmData->id,
avatarText: $name,
),
'country_code' => $countryCode,
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Account */
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {
$this->importOpportunity($pdOpportunity);
$syncCount++;
}
}
$this->logger->info('[Pipedrive] Sync Opportunities completed', [
'team' => $this->team->getId(),
'syncCount' => $syncCount,
]);
} catch (Exception $exception) {
$this->logger->info('[Pipedrive] Failed to sync Opportunities ', [
'team' => $this->team->getId(),
'params' => $parameters,
'strategy' => $strategy,
'reason' => $exception->getMessage(),
'syncedBeforeFailure' => $syncCount,
]);
}
if ($syncCount > 1000) {
$this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [
'team' => $this->team->getId(),
'total' => $syncCount,
]);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = ['crm_id' => $crmId];
try {
$generator = $strategy->fetchOpportunities($parameters);
$pdOpportunity = $generator->current();
} catch (ItemNotFoundException | PipedriveException $e) {
$this->logger->info('[Pipedrive] Failed to sync opportunity', [
'crm_id' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
return $this->importOpportunity($pdOpportunity);
}
/**
* @inheritdoc
*/
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData->deleted) {
return null;
}
if ($crmData->org_id) {
$orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();
if ($account === null) {
$account = $this->syncAccount($orgId);
if ($account === null) {
// For some bizarre reason, the org_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);
return null;
}
}
} elseif ($crmData->person_id) {
// Try to get the organization from the person.
$personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;
$contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();
if ($contact === null || $contact->account_id === null) {
$contact = $this->syncContact($personId);
if ($contact === null) {
// For some bizarre reason, the person_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);
return null;
}
if ($contact->account_id === null) {
$this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());
return null;
}
}
$account = $contact->account;
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $crmData->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$closeDate = null;
if ($crmData->expected_close_date) {
$closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');
}
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
$data = [
'team_id' => $this->team?->getId(),
'account_id' => $account?->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->title, 0, 128),
'value' => $crmData->value,
'currency_code' => CurrencyFormatter::formatCode($crmData->currency),
'close_date' => $closeDate,
'is_closed' => $crmData->close_time !== null,
'is_won' => $crmData->won_time !== null,
'stage_id' => $stage?->getId(),
'record_type_id' => $recordType?->getId(),
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Opportunity $opportunity */
$opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
// import external fields into crm_field_data if present
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdContacts = $this->client->getInstance()->persons()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdContacts->getData() === null) {
return 0;
}
foreach ($pdContacts->getData() as $pdContact) {
// Only sync if previously imported.
if ($this->hasContact($pdContact->id)) {
$this->importContact($pdContact);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
try {
$pdContact = $this->client->getInstance()->persons()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);
}
return $this->importContact($pdContact->getData());
}
private function importContact($crmData): Contact
{
$photoPath = null;
$account = null;
if ($crmData->org_id) {
/**
* Pipedrive API is inconsistent, it may return a string variable, or an object
*/
$crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config
->accounts()
->where('crm_provider_id', $crmProviderId)
->first();
if ($account === null) {
$account = $this->syncAccount($crmProviderId);
$photoPath = $this->teamService->generateAvatar(
$crmData->id,
$crmData->name,
);
} else {
$photoPath = $account->photo_path;
}
}
if ($photoPath === null) {
$photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Contact::class,
fileName: (string) $crmData->id,
avatarText: $crmData->name,
);
}
$ownerId = $profile = null;
if ($crmData->owner_id) {
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
}
$parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);
$mobileNumber = null;
if (isset($crmData->phone[1])) {
$mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);
}
$email = null;
if (isset($crmData->email[0]->value)) {
$email = mb_strimwidth($crmData->email[0]->value, 0, 191);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->name ?? '', 0, 100),
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobileNumber ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData->job_title ?? null,
'photo_path' => $photoPath,
'remotely_created_at' => Carbon::parse($crmData->add_time),
];
/** @var Contact */
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
// Not applicable.
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?\Jiminny\Models\Crm\Profile
{
// Not needed yet.
return null;
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);
/*
// If they have changed, raise a notification to the owner.
$team->owner->notify(
new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)
);
*/
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (Exception $exception) {
Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {
$data = [];
$params = [
'term' => $name,
'limit' => $count,
'start' => $offset,
'item_types' => 'person,organization',
];
$objects = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$objects = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
if (empty($objects['items'])) {
return [];
}
// Build mapped list.
foreach ($objects['items'] as $object) {
$object = $object['item'];
// We only support these object types today.
if (\in_array($object['type'], ['person', 'organization']) === false) {
continue;
}
$objectType = $object['type'] === 'person' ? 'contact' : 'account';
$record = [
'crmId' => $object['id'],
'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),
'name' => $object['name'],
'industry' => null,
'title' => null,
'prospectType' => $objectType,
'phoneNumbers' => [],
];
if (isset($object['organization']['name'])) {
$record['organization'] = $object['organization']['name'];
}
if (isset($object['phones'][0])) {
$parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);
// Add phone number to record.
if (empty($parsedNumber['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $parsedNumber['phone'],
'nationalFormat' => phone_national(null, $parsedNumber['phone']),
'type' => 'phone',
];
}
}
$data[] = $record;
}
return $data;
});
return $data;
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'only_primary_association' => 1,
'status' => 'open',
'sort' => 'update_time DESC',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = 'add_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = 'add_time ASC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
$params['status'] = 'all_not_deleted';
}
$pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
if ($pdOpportunities === null) {
return [];
}
foreach ($pdOpportunities as $pdOpportunity) {
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$record = [
'crmId' => $pdOpportunity->id,
'name' => $pdOpportunity->title,
'value' => $pdOpportunity->formatted_value,
'won' => $pdOpportunity->won_time !== null,
'closed' => $pdOpportunity->status !== 'open',
'stage' => [
'id' => $stage?->id_string ?? '',
'name' => $stage?->name ?? '',
],
'recordType' => [
'id' => $recordType?->id_string ?? '',
'name' => $recordType?->name ?? '',
],
];
if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
$pdActivities = null;
$filters = ['done' => 0];
switch ($objectType) {
case 'contact':
$pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();
break;
case 'account':
// Prioritize looking up activities on the deal (which should be linked on the account anyway).
if ($opportunityId) {
$pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();
}
// If no deal activity, fall back to the organization.
if ($pdActivities === null) {
$pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();
}
break;
}
if ($pdActivities === null) {
return [];
}
foreach ($pdActivities as $pdActivity) {
// Only import active, scheduled tasks in the future.
if ($pdActivity->active_flag) {
$due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');
$data[] = [
'crmId' => $pdActivity->id,
'subject' => $pdActivity->subject,
'due' => Carbon::parse($due)->toIso8601String(),
'type' => $pdActivity->type,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contact = null;
$account = null;
$params = [
'term' => $email,
'item_types' => 'person',
'fields' => 'email',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
$this->logger->info('[Pipedrive] Email match failed', [
'email' => $email,
'reason' => $exception->getMessage(),
]);
return null;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if (
! $contact instanceof Contact
&& ! $account instanceof Account
) {
return null;
}
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (count($pdOpportunities) > 0) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
// Check if the user is internal.
$teamMember = $this->team->users()->where('phone', $phone)->exists();
// Skip the attendee if internal.
if ($teamMember !== false) {
return null;
}
$params = [
'term' => $phone,
'item_types' => 'person,organization',
'fields' => 'phone',
];
$searchResult = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$searchResult = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Phone match failed', [
'phone' => $phone,
'reason' => $e->getMessage(),
]);
return null;
}
if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {
return null;
}
$contact = $this->syncContact($searchResult['items'][0]['item']['id']);
$account = $contact->account;
$countryCode = $this->getCountryCode($contact, $account);
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function getCountryCode($contact, $account): ?string
{
if ($contact && $contact->country_code) {
return $contact->country_code;
} elseif ($account && $account->country_code) {
return $account->country_code;
}
return null;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {
$contact = null;
$account = null;
$params = [
'term' => $name,
'item_types' => 'person',
'fields' => 'name',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Name match failed', [
'name' => $name,
'reason' => $e->getMessage(),
]);
return false;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if ($contact || $account) {
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
return false;
});
return is_array($result) ? $result : null;
}
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->type) {
case Activity::TYPE_CONFERENCE:
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildCallPayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45287
|
1623
|
26
|
2026-05-14T14:29:09.170925+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768949170_m1.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"5","depth":4,"bounds":{"left":0.73194444,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"119","depth":4,"bounds":{"left":0.75277776,"top":0.3122222,"width":0.023611112,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.78055555,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"}]...
|
3621139147992205675
|
-6979357266689274933
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.js* #12066 on JY-20725-handle-HS-search-rate-limit k vabl100% СHandleHubspotRateLimitTest* :8• Thu 14 May 17:29:08QProject v© ReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php:=custom.log© DecorateActivity.php© UserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© LocalSearch.php• LocalSearchlnterface.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.phpSF [jiminny@localhost]© RemoteSearch.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpPlainTextDecorateActivity.phpA HS_local [jiminny@localho:W© Service.php© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging4 console [QAI PROD] X18v C Listeners© ConvertLeadActivities.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.php4 console [PROD]© PurgeLookupCache.php› D Metadata© HubspotPaginationService.php© HandleHubspotRateLimit.phpA console (EU]50classService extends BaseService implements> C MigrationA5 A119 X3 X9 ^DGo jiminny1511private function buildCallPayload(Activity $activity): Activityv Pipedrive0841A3 X4 A V1512> D OpportunitySyncStrategy211m migrations oi1513$type = $this->getCrmType($activity->category);> D ProspectSearchStrategy1514212if ($type === null) {© ApiFields.php=2131515'No mapped CRM type in Pipedrive for "* . Sactivity->category-›name=214m teams wherethrow new Exception( message:© Client.phpm crm_layouts !1516© FieldDefinitions.php215iM crm_layout_ei1517=© PipedriveApiClient.php216IM crm_fields Wi1518$data = [© PipedriveApiException.php=2171519'done' => 1,© Service.php= 218m features;1520'user_id' => $this->profile->crm_provider_id,© TokenStorage.php1521219m team_feature:'due_time' => $activity->scheduled_start_time->format( format: 'H:i'),v D Salesforce220m opportunitie:1522|> C Fields'due_date' => $activity->scheduled_start_time->toDateString(),III2211523'duration' => gmdate( format: 'H:i', $activity->duration),> OpportunityMatcher222m teams;1524'type' => $type->value,> C OpportunitySyncStrategy1525223'subject' => $this->generateActivityTitle(Sactivity),> D ProspectSearchStrategy1526= 224|1.id, CASEWHENv D ServiceTraits'note' => $this->generateActivityDescription(Sactivity),-2251527] + $this->fetchCustomFieldData(Sactivity,objectType: Field::0BJECT_TASK)T BatchSyncTrait.php2261528+ $this->convertActivityAssociations($activity);T FollowupActivityTrait.php1529=227idFROMsocial,D LogActivityTrait.php1530-- 2281 on u.id= sa.:T RecordManipulationsTraireturn Sthis-›upsertActivity(Sactivity, $data);15311|2291..n<->1: on t.T SyncFieldsTrait.php2301532Lid = 1052 and=© Client.php2311 usage© DecorateActivity.php— 232IMaccounts whei1533private function buildTextMessagePayload(Activity $activity): Activity{...}DeleteObjectsTrait.php=233 vactivities1552© FieldDefinitions.php2 usages=234© PavinadRuilder nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1525:43UTF-8Co 4 spaces...
|
45284
|
NULL
|
NULL
|
NULL
|
|
45288
|
1623
|
27
|
2026-05-14T14:29:13.865623+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768953865_m1.jpg...
|
PhpStorm
|
faVsco.js – Pipedrive/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3
9
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Pipedrive;
use Carbon\Carbon;
use Devio\Pipedrive\Exceptions\ItemNotFoundException;
use Devio\Pipedrive\Exceptions\PipedriveException;
use Exception;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\PipedriveInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Events\Users\SocialAccountDisconnected;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\SocialAccountTokenInvalidException;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Log;
use UnexpectedValueException;
class Service extends BaseService implements
PipedriveInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string CALL_HEADER = 'Jiminny Summary';
/**
* @var ClientInterface|Client
*/
protected $client;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)
{
parent::__construct();
$this->client = $client;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Pipedrive';
}
/**
* @inheritdoc
*/
public function setUser(User $user): void
{
try {
parent::setUser($user);
} catch (InvalidArgumentException $exception) {
// In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.
if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&
$exception->getMessage() === 'Required option not passed: "access_token"') {
// Something terrible happened to their token, they need to reconnect.
$this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);
event(new SocialAccountDisconnected($this->client->oauthAccount));
}
throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');
}
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
switch ($fieldType) {
case Field::TYPE_DATE:
$value = $internal ? Carbon::parse($fieldValue) : $fieldValue;
break;
default:
$value = $fieldValue;
}
return $value;
}
/**
* Gets the valid fields for a given Object via the property APIs.
*
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
switch ($crmObject) {
case 'task':
$properties = $this->client->getInstance()->activityFields();
break;
case 'account':
$properties = $this->client->getInstance()->organizationFields();
break;
case 'contact':
$properties = $this->client->getInstance()->personFields();
break;
case 'opportunity':
$properties = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException();
}
$fields = [];
try {
$response = $properties->all();
if ($response->isSuccess() === false) {
throw new Exception($response->getContent(), $response->getStatusCode());
}
foreach ($response->getData() as $property) {
$fields[] = ['label' => $property->name, 'name' => $property->key];
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
return;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
$field->description = null;
$field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($crmField->field_type);
$field->is_selectable = $crmField->active_flag;
$field->save();
}
}
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'enum':
case 'stage':
case 'status':
return Field::TYPE_PICKLIST;
case 'varchar':
return Field::TYPE_TEXT;
case 'int':
case 'double':
return Field::TYPE_NUMBER;
case 'text':
return Field::TYPE_TEXTAREA;
case 'monetary':
return Field::TYPE_CURRENCY;
case Field::TYPE_DATE:
case Field::TYPE_TIME:
case Field::TYPE_PHONE:
return $fieldType;
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException('Invalid field type "' . $field->object_type . '" for field ' . $field->id . '.');
}
if ($field->crm_provider_id == 'stage_id') {
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();
foreach ($dealStages as $i => $dealStage) {
$values = [
'value' => $dealStage->id,
'label' => $dealStage->name,
'sequence' => $i,
];
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $dealStage->id,
], $values);
}
}
return $fieldValues;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
// Import all active values.
if (property_exists($crmField, 'options')) {
foreach ($crmField->options as $i => $option) {
$values[] = [
'value' => $option->id,
'label' => $option->label,
'sequence' => $i,
];
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
return $fieldValues;
}
/**
* @inheritdoc
*
* @throws SocialAccountTokenInvalidException
* @throws PipedriveException
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// We create a business process to contain the pipeline, and later store all stages against it.
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$businessProcess = $this->importPipelineData($pipeline);
$stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);
if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {
$missingStage = $stage;
}
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
// Pipedrive doesn't use leads.
return 0;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
// Pipedrive doesn't use leads.
return null;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdAccounts = $this->client->getInstance()->organizations()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdAccounts->getData() === null) {
return 0;
}
foreach ($pdAccounts->getData() as $pdAccount) {
// Only sync if previously imported.
if ($this->hasAccount($pdAccount->id)) {
$this->importAccount($pdAccount);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
try {
$hsAccount = $this->client->getInstance()->organizations()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);
}
return $this->importAccount($hsAccount->getData());
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = $crmData->country_code;
if ($countryCode === null && $crmData->address_country) {
$countryCode = $this->convertCountryNameToCode($crmData->address_country);
}
$name = $crmData->name;
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
/**
* Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.
* These are real samples from API results:
* { ... owner_id: 23696001, ...}
* OR
* {
* ...
* owner_id: {
* active_flag: false,
* id: 12972717,
* name: 'name here',
* value: 12972717
* }
* }
*/
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Account::class,
fileName: (string) $crmData->id,
avatarText: $name,
),
'country_code' => $countryCode,
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Account */
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {
$this->importOpportunity($pdOpportunity);
$syncCount++;
}
}
$this->logger->info('[Pipedrive] Sync Opportunities completed', [
'team' => $this->team->getId(),
'syncCount' => $syncCount,
]);
} catch (Exception $exception) {
$this->logger->info('[Pipedrive] Failed to sync Opportunities ', [
'team' => $this->team->getId(),
'params' => $parameters,
'strategy' => $strategy,
'reason' => $exception->getMessage(),
'syncedBeforeFailure' => $syncCount,
]);
}
if ($syncCount > 1000) {
$this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [
'team' => $this->team->getId(),
'total' => $syncCount,
]);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = ['crm_id' => $crmId];
try {
$generator = $strategy->fetchOpportunities($parameters);
$pdOpportunity = $generator->current();
} catch (ItemNotFoundException | PipedriveException $e) {
$this->logger->info('[Pipedrive] Failed to sync opportunity', [
'crm_id' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
return $this->importOpportunity($pdOpportunity);
}
/**
* @inheritdoc
*/
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData->deleted) {
return null;
}
if ($crmData->org_id) {
$orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();
if ($account === null) {
$account = $this->syncAccount($orgId);
if ($account === null) {
// For some bizarre reason, the org_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);
return null;
}
}
} elseif ($crmData->person_id) {
// Try to get the organization from the person.
$personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;
$contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();
if ($contact === null || $contact->account_id === null) {
$contact = $this->syncContact($personId);
if ($contact === null) {
// For some bizarre reason, the person_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);
return null;
}
if ($contact->account_id === null) {
$this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());
return null;
}
}
$account = $contact->account;
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $crmData->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$closeDate = null;
if ($crmData->expected_close_date) {
$closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');
}
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
$data = [
'team_id' => $this->team?->getId(),
'account_id' => $account?->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->title, 0, 128),
'value' => $crmData->value,
'currency_code' => CurrencyFormatter::formatCode($crmData->currency),
'close_date' => $closeDate,
'is_closed' => $crmData->close_time !== null,
'is_won' => $crmData->won_time !== null,
'stage_id' => $stage?->getId(),
'record_type_id' => $recordType?->getId(),
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Opportunity $opportunity */
$opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
// import external fields into crm_field_data if present
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdContacts = $this->client->getInstance()->persons()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdContacts->getData() === null) {
return 0;
}
foreach ($pdContacts->getData() as $pdContact) {
// Only sync if previously imported.
if ($this->hasContact($pdContact->id)) {
$this->importContact($pdContact);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
try {
$pdContact = $this->client->getInstance()->persons()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);
}
return $this->importContact($pdContact->getData());
}
private function importContact($crmData): Contact
{
$photoPath = null;
$account = null;
if ($crmData->org_id) {
/**
* Pipedrive API is inconsistent, it may return a string variable, or an object
*/
$crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config
->accounts()
->where('crm_provider_id', $crmProviderId)
->first();
if ($account === null) {
$account = $this->syncAccount($crmProviderId);
$photoPath = $this->teamService->generateAvatar(
$crmData->id,
$crmData->name,
);
} else {
$photoPath = $account->photo_path;
}
}
if ($photoPath === null) {
$photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Contact::class,
fileName: (string) $crmData->id,
avatarText: $crmData->name,
);
}
$ownerId = $profile = null;
if ($crmData->owner_id) {
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
}
$parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);
$mobileNumber = null;
if (isset($crmData->phone[1])) {
$mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);
}
$email = null;
if (isset($crmData->email[0]->value)) {
$email = mb_strimwidth($crmData->email[0]->value, 0, 191);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->name ?? '', 0, 100),
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobileNumber ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData->job_title ?? null,
'photo_path' => $photoPath,
'remotely_created_at' => Carbon::parse($crmData->add_time),
];
/** @var Contact */
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
// Not applicable.
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?\Jiminny\Models\Crm\Profile
{
// Not needed yet.
return null;
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);
/*
// If they have changed, raise a notification to the owner.
$team->owner->notify(
new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)
);
*/
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (Exception $exception) {
Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {
$data = [];
$params = [
'term' => $name,
'limit' => $count,
'start' => $offset,
'item_types' => 'person,organization',
];
$objects = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$objects = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
if (empty($objects['items'])) {
return [];
}
// Build mapped list.
foreach ($objects['items'] as $object) {
$object = $object['item'];
// We only support these object types today.
if (\in_array($object['type'], ['person', 'organization']) === false) {
continue;
}
$objectType = $object['type'] === 'person' ? 'contact' : 'account';
$record = [
'crmId' => $object['id'],
'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),
'name' => $object['name'],
'industry' => null,
'title' => null,
'prospectType' => $objectType,
'phoneNumbers' => [],
];
if (isset($object['organization']['name'])) {
$record['organization'] = $object['organization']['name'];
}
if (isset($object['phones'][0])) {
$parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);
// Add phone number to record.
if (empty($parsedNumber['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $parsedNumber['phone'],
'nationalFormat' => phone_national(null, $parsedNumber['phone']),
'type' => 'phone',
];
}
}
$data[] = $record;
}
return $data;
});
return $data;
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'only_primary_association' => 1,
'status' => 'open',
'sort' => 'update_time DESC',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = 'add_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = 'add_time ASC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
$params['status'] = 'all_not_deleted';
}
$pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
if ($pdOpportunities === null) {
return [];
}
foreach ($pdOpportunities as $pdOpportunity) {
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$record = [
'crmId' => $pdOpportunity->id,
'name' => $pdOpportunity->title,
'value' => $pdOpportunity->formatted_value,
'won' => $pdOpportunity->won_time !== null,
'closed' => $pdOpportunity->status !== 'open',
'stage' => [
'id' => $stage?->id_string ?? '',
'name' => $stage?->name ?? '',
],
'recordType' => [
'id' => $recordType?->id_string ?? '',
'name' => $recordType?->name ?? '',
],
];
if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
$pdActivities = null;
$filters = ['done' => 0];
switch ($objectType) {
case 'contact':
$pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();
break;
case 'account':
// Prioritize looking up activities on the deal (which should be linked on the account anyway).
if ($opportunityId) {
$pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();
}
// If no deal activity, fall back to the organization.
if ($pdActivities === null) {
$pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();
}
break;
}
if ($pdActivities === null) {
return [];
}
foreach ($pdActivities as $pdActivity) {
// Only import active, scheduled tasks in the future.
if ($pdActivity->active_flag) {
$due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');
$data[] = [
'crmId' => $pdActivity->id,
'subject' => $pdActivity->subject,
'due' => Carbon::parse($due)->toIso8601String(),
'type' => $pdActivity->type,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contact = null;
$account = null;
$params = [
'term' => $email,
'item_types' => 'person',
'fields' => 'email',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
$this->logger->info('[Pipedrive] Email match failed', [
'email' => $email,
'reason' => $exception->getMessage(),
]);
return null;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if (
! $contact instanceof Contact
&& ! $account instanceof Account
) {
return null;
}
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (count($pdOpportunities) > 0) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
// Check if the user is internal.
$teamMember = $this->team->users()->where('phone', $phone)->exists();
// Skip the attendee if internal.
if ($teamMember !== false) {
return null;
}
$params = [
'term' => $phone,
'item_types' => 'person,organization',
'fields' => 'phone',
];
$searchResult = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$searchResult = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Phone match failed', [
'phone' => $phone,
'reason' => $e->getMessage(),
]);
return null;
}
if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {
return null;
}
$contact = $this->syncContact($searchResult['items'][0]['item']['id']);
$account = $contact->account;
$countryCode = $this->getCountryCode($contact, $account);
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function getCountryCode($contact, $account): ?string
{
if ($contact && $contact->country_code) {
return $contact->country_code;
} elseif ($account && $account->country_code) {
return $account->country_code;
}
return null;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {
$contact = null;
$account = null;
$params = [
'term' => $name,
'item_types' => 'person',
'fields' => 'name',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Name match failed', [
'name' => $name,
'reason' => $e->getMessage(),
]);
return false;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if ($contact || $account) {
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
return false;
});
return is_array($result) ? $result : null;
}
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->type) {
case Activity::TYPE_CONFERENCE:
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildCallPayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"5","depth":4,"bounds":{"left":0.73194444,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"119","depth":4,"bounds":{"left":0.75277776,"top":0.3122222,"width":0.023611112,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.78055555,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.80138886,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Pipedrive;\n\nuse Carbon\\Carbon;\nuse Devio\\Pipedrive\\Exceptions\\ItemNotFoundException;\nuse Devio\\Pipedrive\\Exceptions\\PipedriveException;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\PipedriveInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Events\\Users\\SocialAccountDisconnected;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\SocialAccountTokenInvalidException;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Log;\nuse UnexpectedValueException;\n\nclass Service extends BaseService implements\n PipedriveInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string CALL_HEADER = 'Jiminny Summary';\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)\n {\n parent::__construct();\n\n $this->client = $client;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Pipedrive';\n }\n\n /**\n * @inheritdoc\n */\n public function setUser(User $user): void\n {\n try {\n parent::setUser($user);\n } catch (InvalidArgumentException $exception) {\n // In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.\n if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&\n $exception->getMessage() === 'Required option not passed: \"access_token\"') {\n // Something terrible happened to their token, they need to reconnect.\n $this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);\n\n event(new SocialAccountDisconnected($this->client->oauthAccount));\n }\n\n throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');\n }\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n switch ($fieldType) {\n case Field::TYPE_DATE:\n $value = $internal ? Carbon::parse($fieldValue) : $fieldValue;\n\n break;\n\n default:\n $value = $fieldValue;\n }\n\n return $value;\n }\n\n /**\n * Gets the valid fields for a given Object via the property APIs.\n *\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n switch ($crmObject) {\n case 'task':\n $properties = $this->client->getInstance()->activityFields();\n\n break;\n\n case 'account':\n $properties = $this->client->getInstance()->organizationFields();\n\n break;\n\n case 'contact':\n $properties = $this->client->getInstance()->personFields();\n\n break;\n\n case 'opportunity':\n $properties = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException();\n }\n\n $fields = [];\n\n try {\n $response = $properties->all();\n\n if ($response->isSuccess() === false) {\n throw new Exception($response->getContent(), $response->getStatusCode());\n }\n\n foreach ($response->getData() as $property) {\n $fields[] = ['label' => $property->name, 'name' => $property->key];\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n return;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n $field->description = null;\n $field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($crmField->field_type);\n $field->is_selectable = $crmField->active_flag;\n $field->save();\n }\n }\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'enum':\n case 'stage':\n case 'status':\n return Field::TYPE_PICKLIST;\n\n case 'varchar':\n return Field::TYPE_TEXT;\n\n case 'int':\n case 'double':\n return Field::TYPE_NUMBER;\n\n case 'text':\n return Field::TYPE_TEXTAREA;\n\n case 'monetary':\n return Field::TYPE_CURRENCY;\n\n case Field::TYPE_DATE:\n case Field::TYPE_TIME:\n case Field::TYPE_PHONE:\n return $fieldType;\n\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException('Invalid field type \"' . $field->object_type . '\" for field ' . $field->id . '.');\n }\n\n if ($field->crm_provider_id == 'stage_id') {\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n foreach ($pipelines as $pipeline) {\n $dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();\n foreach ($dealStages as $i => $dealStage) {\n $values = [\n 'value' => $dealStage->id,\n 'label' => $dealStage->name,\n 'sequence' => $i,\n ];\n\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $dealStage->id,\n ], $values);\n }\n }\n\n return $fieldValues;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n // Import all active values.\n if (property_exists($crmField, 'options')) {\n foreach ($crmField->options as $i => $option) {\n $values[] = [\n 'value' => $option->id,\n 'label' => $option->label,\n 'sequence' => $i,\n ];\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n *\n * @throws SocialAccountTokenInvalidException\n * @throws PipedriveException\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // We create a business process to contain the pipeline, and later store all stages against it.\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n\n foreach ($pipelines as $pipeline) {\n $businessProcess = $this->importPipelineData($pipeline);\n\n $stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);\n if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {\n $missingStage = $stage;\n }\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n // Pipedrive doesn't use leads.\n return 0;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n // Pipedrive doesn't use leads.\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdAccounts = $this->client->getInstance()->organizations()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdAccounts->getData() === null) {\n return 0;\n }\n\n foreach ($pdAccounts->getData() as $pdAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($pdAccount->id)) {\n $this->importAccount($pdAccount);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $hsAccount = $this->client->getInstance()->organizations()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importAccount($hsAccount->getData());\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData->country_code;\n if ($countryCode === null && $crmData->address_country) {\n $countryCode = $this->convertCountryNameToCode($crmData->address_country);\n }\n\n $name = $crmData->name;\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n /**\n * Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.\n * These are real samples from API results:\n * { ... owner_id: 23696001, ...}\n * OR\n * {\n * ...\n * owner_id: {\n * active_flag: false,\n * id: 12972717,\n * name: 'name here',\n * value: 12972717\n * }\n * }\n */\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Account::class,\n fileName: (string) $crmData->id,\n avatarText: $name,\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Account */\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {\n $this->importOpportunity($pdOpportunity);\n $syncCount++;\n }\n }\n\n $this->logger->info('[Pipedrive] Sync Opportunities completed', [\n 'team' => $this->team->getId(),\n 'syncCount' => $syncCount,\n ]);\n } catch (Exception $exception) {\n $this->logger->info('[Pipedrive] Failed to sync Opportunities ', [\n 'team' => $this->team->getId(),\n 'params' => $parameters,\n 'strategy' => $strategy,\n 'reason' => $exception->getMessage(),\n 'syncedBeforeFailure' => $syncCount,\n ]);\n }\n\n if ($syncCount > 1000) {\n $this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [\n 'team' => $this->team->getId(),\n 'total' => $syncCount,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = ['crm_id' => $crmId];\n\n try {\n $generator = $strategy->fetchOpportunities($parameters);\n $pdOpportunity = $generator->current();\n } catch (ItemNotFoundException | PipedriveException $e) {\n $this->logger->info('[Pipedrive] Failed to sync opportunity', [\n 'crm_id' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n return $this->importOpportunity($pdOpportunity);\n }\n\n /**\n * @inheritdoc\n */\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData->deleted) {\n return null;\n }\n\n if ($crmData->org_id) {\n $orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n $account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($orgId);\n\n if ($account === null) {\n // For some bizarre reason, the org_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);\n\n return null;\n }\n }\n } elseif ($crmData->person_id) {\n // Try to get the organization from the person.\n $personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;\n $contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();\n\n if ($contact === null || $contact->account_id === null) {\n $contact = $this->syncContact($personId);\n\n if ($contact === null) {\n // For some bizarre reason, the person_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);\n\n return null;\n }\n\n if ($contact->account_id === null) {\n $this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());\n\n return null;\n }\n }\n\n $account = $contact->account;\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $crmData->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $closeDate = null;\n if ($crmData->expected_close_date) {\n $closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');\n }\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n $data = [\n 'team_id' => $this->team?->getId(),\n 'account_id' => $account?->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->title, 0, 128),\n 'value' => $crmData->value,\n 'currency_code' => CurrencyFormatter::formatCode($crmData->currency),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData->close_time !== null,\n 'is_won' => $crmData->won_time !== null,\n 'stage_id' => $stage?->getId(),\n 'record_type_id' => $recordType?->getId(),\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdContacts = $this->client->getInstance()->persons()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdContacts->getData() === null) {\n return 0;\n }\n\n foreach ($pdContacts->getData() as $pdContact) {\n // Only sync if previously imported.\n if ($this->hasContact($pdContact->id)) {\n $this->importContact($pdContact);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $pdContact = $this->client->getInstance()->persons()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importContact($pdContact->getData());\n }\n\n private function importContact($crmData): Contact\n {\n $photoPath = null;\n $account = null;\n if ($crmData->org_id) {\n /**\n * Pipedrive API is inconsistent, it may return a string variable, or an object\n */\n $crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n\n $account = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmProviderId)\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmProviderId);\n $photoPath = $this->teamService->generateAvatar(\n $crmData->id,\n $crmData->name,\n );\n } else {\n $photoPath = $account->photo_path;\n }\n }\n\n if ($photoPath === null) {\n $photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Contact::class,\n fileName: (string) $crmData->id,\n avatarText: $crmData->name,\n );\n }\n\n $ownerId = $profile = null;\n if ($crmData->owner_id) {\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n }\n\n $parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);\n\n $mobileNumber = null;\n if (isset($crmData->phone[1])) {\n $mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);\n }\n\n $email = null;\n if (isset($crmData->email[0]->value)) {\n $email = mb_strimwidth($crmData->email[0]->value, 0, 191);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->name ?? '', 0, 100),\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobileNumber ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData->job_title ?? null,\n 'photo_path' => $photoPath,\n 'remotely_created_at' => Carbon::parse($crmData->add_time),\n ];\n\n /** @var Contact */\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n // Not applicable.\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?\\Jiminny\\Models\\Crm\\Profile\n {\n // Not needed yet.\n return null;\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);\n\n /*\n // If they have changed, raise a notification to the owner.\n $team->owner->notify(\n new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)\n );\n */\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (Exception $exception) {\n Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {\n $data = [];\n $params = [\n 'term' => $name,\n 'limit' => $count,\n 'start' => $offset,\n 'item_types' => 'person,organization',\n ];\n\n $objects = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $objects = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n if (empty($objects['items'])) {\n return [];\n }\n\n // Build mapped list.\n foreach ($objects['items'] as $object) {\n $object = $object['item'];\n\n // We only support these object types today.\n if (\\in_array($object['type'], ['person', 'organization']) === false) {\n continue;\n }\n\n $objectType = $object['type'] === 'person' ? 'contact' : 'account';\n $record = [\n 'crmId' => $object['id'],\n 'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),\n 'name' => $object['name'],\n 'industry' => null,\n 'title' => null,\n 'prospectType' => $objectType,\n 'phoneNumbers' => [],\n ];\n\n if (isset($object['organization']['name'])) {\n $record['organization'] = $object['organization']['name'];\n }\n\n if (isset($object['phones'][0])) {\n $parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);\n\n // Add phone number to record.\n if (empty($parsedNumber['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national(null, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n }\n\n $data[] = $record;\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'only_primary_association' => 1,\n 'status' => 'open',\n 'sort' => 'update_time DESC',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = 'add_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = 'add_time ASC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n $params['status'] = 'all_not_deleted';\n }\n\n $pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n if ($pdOpportunities === null) {\n return [];\n }\n\n foreach ($pdOpportunities as $pdOpportunity) {\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $record = [\n 'crmId' => $pdOpportunity->id,\n 'name' => $pdOpportunity->title,\n 'value' => $pdOpportunity->formatted_value,\n 'won' => $pdOpportunity->won_time !== null,\n 'closed' => $pdOpportunity->status !== 'open',\n 'stage' => [\n 'id' => $stage?->id_string ?? '',\n 'name' => $stage?->name ?? '',\n ],\n 'recordType' => [\n 'id' => $recordType?->id_string ?? '',\n 'name' => $recordType?->name ?? '',\n ],\n ];\n\n if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n $pdActivities = null;\n $filters = ['done' => 0];\n switch ($objectType) {\n case 'contact':\n $pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();\n\n break;\n case 'account':\n // Prioritize looking up activities on the deal (which should be linked on the account anyway).\n if ($opportunityId) {\n $pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();\n }\n\n // If no deal activity, fall back to the organization.\n if ($pdActivities === null) {\n $pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();\n }\n\n break;\n }\n\n if ($pdActivities === null) {\n return [];\n }\n\n foreach ($pdActivities as $pdActivity) {\n // Only import active, scheduled tasks in the future.\n if ($pdActivity->active_flag) {\n $due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');\n $data[] = [\n 'crmId' => $pdActivity->id,\n 'subject' => $pdActivity->subject,\n 'due' => Carbon::parse($due)->toIso8601String(),\n 'type' => $pdActivity->type,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $email,\n 'item_types' => 'person',\n 'fields' => 'email',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n $this->logger->info('[Pipedrive] Email match failed', [\n 'email' => $email,\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if (\n ! $contact instanceof Contact\n && ! $account instanceof Account\n ) {\n return null;\n }\n\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n if (count($pdOpportunities) > 0) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember !== false) {\n return null;\n }\n\n $params = [\n 'term' => $phone,\n 'item_types' => 'person,organization',\n 'fields' => 'phone',\n ];\n\n $searchResult = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $searchResult = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {\n return null;\n }\n\n $contact = $this->syncContact($searchResult['items'][0]['item']['id']);\n $account = $contact->account;\n\n $countryCode = $this->getCountryCode($contact, $account);\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function getCountryCode($contact, $account): ?string\n {\n if ($contact && $contact->country_code) {\n return $contact->country_code;\n } elseif ($account && $account->country_code) {\n return $account->country_code;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $name,\n 'item_types' => 'person',\n 'fields' => 'name',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Name match failed', [\n 'name' => $name,\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if ($contact || $account) {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n return false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'person_id' => $activity->hasContact() ? $activity->getContact()->getCrmProviderId() : null,\n 'org_id' => $activity->hasAccount() ? $activity->getAccount()->getCrmProviderId() : null,\n 'deal_id' => $activity->hasOpportunity() ? $activity->getOpportunity()->getCrmProviderId() : null,\n ];\n }\n\n private function buildCallPayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->scheduled_start_time->format('H:i'),\n 'due_date' => $activity->scheduled_start_time->toDateString(),\n 'duration' => gmdate('H:i', $activity->duration),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->fetchCustomFieldData($activity, Field::OBJECT_TASK)\n + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->created_at->format('H:i'),\n 'due_date' => $activity->created_at->toDateString(),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function upsertActivity(Activity $activity, array $data): Activity\n {\n // The activity should be logged under an existing activity.\n if ($activity->hasCrmProviderId()) {\n $existingActivity = $this->client->getActivity($activity->getCrmProviderId());\n\n if ($existingActivity && $existingData = $existingActivity->getData()) {\n $existingData = (array) $existingData;\n $data = $this->updateDescription($existingData, $data);\n $data = $this->updateProspectData($existingData, $data);\n\n // Just update the existing engagement with any fresh details.\n $this->client->updateActivity($activity->getCrmProviderId(), $data);\n }\n } else {\n $pdActivity = $this->client->createActivity($data);\n\n $activity->crm_provider_id = $pdActivity->getData()->id;\n $activity->save();\n }\n\n return $activity;\n }\n\n private function updateDescription(array $crmActivityData, array $payloadData): array\n {\n $crmActivityNote = $crmActivityData['note'] ?? null;\n\n if (! empty($crmActivityNote)) {\n if (! str_contains($crmActivityNote, self::CALL_HEADER)) {\n $payloadData['note'] = $crmActivityNote . \"\\n\\n\" . $payloadData['note'];\n } else {\n $payloadData['note'] = $crmActivityNote;\n }\n }\n\n return $payloadData;\n }\n\n private function updateProspectData($crmActivityData, array $data): array\n {\n $changedData = [];\n if ($crmActivityData['person_id'] && ! isset($data['person_id'])) {\n $changedData['person_id'] = $crmActivityData['person_id'];\n $data['person_id'] = $crmActivityData['person_id'];\n $data['org_id'] = null;\n $data['deal_id'] = null;\n } elseif (isset($data['person_id']) && $data['person_id'] != $crmActivityData['person_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in person_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['person_id'],\n 'crm_activity_data' => $crmActivityData['person_id'],\n ]);\n }\n\n if ($crmActivityData['org_id'] && ! isset($data['org_id'])) {\n $changedData['org_id'] = $crmActivityData['org_id'];\n $data['org_id'] = $crmActivityData['org_id'];\n $data['deal_id'] = null;\n } elseif (isset($data['org_id']) && $data['org_id'] != $crmActivityData['org_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in org_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['org_id'],\n 'crm_activity_data' => $crmActivityData['org_id'],\n ]);\n }\n\n if ($crmActivityData['deal_id'] && ! isset($data['deal_id'])) {\n $changedData['deal_id'] = $crmActivityData['deal_id'];\n $data['deal_id'] = $crmActivityData['deal_id'];\n } elseif (isset($data['deal_id']) && $data['deal_id'] != $crmActivityData['deal_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in deal_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['deal_id'],\n 'crm_activity_data' => $crmActivityData['deal_id'],\n ]);\n }\n\n if (! empty($changedData)) {\n $this->logger->info('[Pipedrive] Updated activity associations', $changedData);\n }\n\n return $data;\n }\n\n private function generateActivityTitle(Activity $activity): string\n {\n if ($activity->hasTitle()) {\n $title = $activity->title;\n } elseif ($activity->playbook_category_id) {\n $title = $activity->category->name;\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n self::CALL_HEADER\n );\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->hasTitle()) {\n // Insert the activity type since there is no native field.\n $description .= sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n $activity->category->name,\n );\n }\n\n if ($activity->isTypeSoftPhone()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">Review in Jiminny</a>'\n . ' ▶️'\n . '</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->type === Activity::TYPE_CONFERENCE) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity type field.\n if (empty($fields['type'])) {\n return null;\n }\n\n if (empty($fields['subject'])) {\n // We need to convert the name correctly.\n $playbook = $this->getPlaybook($activity->getUser());\n $type = $playbook->activityField->values()->where('value', $fields['type'])->first();\n $subject = ($type->label ?? $fields['type']) . ' with ' . $activity->prospect_name;\n } else {\n $subject = $fields['subject'];\n }\n\n $data = [\n 'done' => 0,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_date' => $fields['due_date'] ?? date('Y-m-d'),\n 'due_time' => $fields['due_time'] ?? null,\n 'subject' => $subject,\n 'type' => $fields['type'],\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->activities()->add($data);\n\n // We don't actually create a corresponding activity object on our side yet.\n return $pdActivity->getData()->id;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, self::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'content' => $transcripts,\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->notes()->add($data);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $pdActivity->getData()->id;\n $transcription->save();\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->convertObjectTypeToResource($objectType)->update($objectId, $data);\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n $record = $this->convertObjectTypeToResource($objectType)->find($objectId)->getData();\n\n // We could map the fields requested here before returning.\n return $record ? (array) $record : [];\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case parent::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals();\n\n case parent::OBJECT_CONTACT:\n return $this->client->getInstance()->persons();\n\n case parent::OBJECT_ACCOUNT:\n return $this->client->getInstance()->organizations();\n\n case parent::OBJECT_TASK:\n return $this->client->getInstance()->activities();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \".$objectType.\"');\n }\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, [\n 'stage_id' => $stage->crm_provider_id,\n ]);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->field->crm_provider_id => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n switch ($objectType) {\n case 'account':\n $url = $this->config->crm_base_url . '/organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $this->config->crm_base_url . '/person/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $this->config->crm_base_url . '/deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Pipedrive UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n public function importPipeline(int $pipelineId): ?BusinessProcess\n {\n try {\n $pipeline = $this->client->getInstance()->pipelines()->find($pipelineId)->getData();\n } catch (ItemNotFoundException $exception) {\n return null;\n }\n\n if ($pipeline === null) {\n return null;\n }\n\n return $this->importPipelineData($pipeline);\n }\n\n private function importPipelineData(mixed $pipeline): BusinessProcess\n {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $pipeline->active,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'is_selectable' => $pipeline->active,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n return $businessProcess;\n }\n\n private function importStagesForBusinessProcess(BusinessProcess $businessProcess, ?string $missingId): ?Stage\n {\n $missingStage = null;\n $stages = [];\n $dealStages = $this->client->getInstance()\n ->stages()\n ->all(['pipeline_id' => (int) $businessProcess->crm_provider_id])\n ->getData();\n\n foreach ($dealStages as $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->importStage($dealStage);\n\n if ($missingId !== null && $stage->crm_provider_id == $missingId) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n\n return $missingStage;\n }\n\n private function importStage(mixed $dealStage): Stage\n {\n return $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage->name, 0, 50),\n 'label' => mb_strimwidth($dealStage->name, 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $dealStage->order_nr,\n 'is_selectable' => $dealStage->active_flag,\n 'probability' => $dealStage->deal_probability,\n ]);\n }\n\n private function getBusinessProcesses(string $pipelineId): ?BusinessProcess\n {\n return $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $pipelineId)\n ->first();\n }\n\n private function getStage(?BusinessProcess $businessProcess, string $stageId): ?Stage\n {\n return $businessProcess\n ?->stages()\n ->where('crm_provider_id', $stageId)\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if (! is_numeric($crmProviderId)) {\n $this->logger->warning('[Pipedrive] Invalid activity ID format', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n $activity = $this->client->getActivity($crmProviderId);\n\n return ($activity->active_flag ?? false) === true;\n } catch (HttpNotFoundException) {\n // Activity not found in CRM - this is expected and permanent\n $this->logger->info('[Pipedrive] Activity not found during verification', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Pipedrive;\n\nuse Carbon\\Carbon;\nuse Devio\\Pipedrive\\Exceptions\\ItemNotFoundException;\nuse Devio\\Pipedrive\\Exceptions\\PipedriveException;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\PipedriveInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Events\\Users\\SocialAccountDisconnected;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\SocialAccountTokenInvalidException;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Log;\nuse UnexpectedValueException;\n\nclass Service extends BaseService implements\n PipedriveInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string CALL_HEADER = 'Jiminny Summary';\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)\n {\n parent::__construct();\n\n $this->client = $client;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Pipedrive';\n }\n\n /**\n * @inheritdoc\n */\n public function setUser(User $user): void\n {\n try {\n parent::setUser($user);\n } catch (InvalidArgumentException $exception) {\n // In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.\n if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&\n $exception->getMessage() === 'Required option not passed: \"access_token\"') {\n // Something terrible happened to their token, they need to reconnect.\n $this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);\n\n event(new SocialAccountDisconnected($this->client->oauthAccount));\n }\n\n throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');\n }\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n switch ($fieldType) {\n case Field::TYPE_DATE:\n $value = $internal ? Carbon::parse($fieldValue) : $fieldValue;\n\n break;\n\n default:\n $value = $fieldValue;\n }\n\n return $value;\n }\n\n /**\n * Gets the valid fields for a given Object via the property APIs.\n *\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n switch ($crmObject) {\n case 'task':\n $properties = $this->client->getInstance()->activityFields();\n\n break;\n\n case 'account':\n $properties = $this->client->getInstance()->organizationFields();\n\n break;\n\n case 'contact':\n $properties = $this->client->getInstance()->personFields();\n\n break;\n\n case 'opportunity':\n $properties = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException();\n }\n\n $fields = [];\n\n try {\n $response = $properties->all();\n\n if ($response->isSuccess() === false) {\n throw new Exception($response->getContent(), $response->getStatusCode());\n }\n\n foreach ($response->getData() as $property) {\n $fields[] = ['label' => $property->name, 'name' => $property->key];\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n return;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n $field->description = null;\n $field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($crmField->field_type);\n $field->is_selectable = $crmField->active_flag;\n $field->save();\n }\n }\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'enum':\n case 'stage':\n case 'status':\n return Field::TYPE_PICKLIST;\n\n case 'varchar':\n return Field::TYPE_TEXT;\n\n case 'int':\n case 'double':\n return Field::TYPE_NUMBER;\n\n case 'text':\n return Field::TYPE_TEXTAREA;\n\n case 'monetary':\n return Field::TYPE_CURRENCY;\n\n case Field::TYPE_DATE:\n case Field::TYPE_TIME:\n case Field::TYPE_PHONE:\n return $fieldType;\n\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n switch ($field->object_type) {\n case Field::OBJECT_TASK:\n $crmFields = $this->client->getInstance()->activityFields();\n\n break;\n\n case Field::OBJECT_ACCOUNT:\n $crmFields = $this->client->getInstance()->organizationFields();\n\n break;\n\n case Field::OBJECT_CONTACT:\n $crmFields = $this->client->getInstance()->personFields();\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n $crmFields = $this->client->getInstance()->dealFields();\n\n break;\n\n default:\n throw new InvalidArgumentException('Invalid field type \"' . $field->object_type . '\" for field ' . $field->id . '.');\n }\n\n if ($field->crm_provider_id == 'stage_id') {\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n foreach ($pipelines as $pipeline) {\n $dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();\n foreach ($dealStages as $i => $dealStage) {\n $values = [\n 'value' => $dealStage->id,\n 'label' => $dealStage->name,\n 'sequence' => $i,\n ];\n\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $dealStage->id,\n ], $values);\n }\n }\n\n return $fieldValues;\n }\n\n // Sadly we must traverse the entire list because they don't allow to get an individual field by key.\n foreach ($crmFields->all()->getData() as $crmField) {\n if ($crmField->key === $field->crm_provider_id) {\n // Import all active values.\n if (property_exists($crmField, 'options')) {\n foreach ($crmField->options as $i => $option) {\n $values[] = [\n 'value' => $option->id,\n 'label' => $option->label,\n 'sequence' => $i,\n ];\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n *\n * @throws SocialAccountTokenInvalidException\n * @throws PipedriveException\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // We create a business process to contain the pipeline, and later store all stages against it.\n $pipelines = $this->client->getInstance()->pipelines()->all()->getData();\n\n foreach ($pipelines as $pipeline) {\n $businessProcess = $this->importPipelineData($pipeline);\n\n $stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);\n if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {\n $missingStage = $stage;\n }\n }\n } catch (PipedriveException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n // Pipedrive doesn't use leads.\n return 0;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n // Pipedrive doesn't use leads.\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdAccounts = $this->client->getInstance()->organizations()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdAccounts->getData() === null) {\n return 0;\n }\n\n foreach ($pdAccounts->getData() as $pdAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($pdAccount->id)) {\n $this->importAccount($pdAccount);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $hsAccount = $this->client->getInstance()->organizations()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importAccount($hsAccount->getData());\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData->country_code;\n if ($countryCode === null && $crmData->address_country) {\n $countryCode = $this->convertCountryNameToCode($crmData->address_country);\n }\n\n $name = $crmData->name;\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n /**\n * Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.\n * These are real samples from API results:\n * { ... owner_id: 23696001, ...}\n * OR\n * {\n * ...\n * owner_id: {\n * active_flag: false,\n * id: 12972717,\n * name: 'name here',\n * value: 12972717\n * }\n * }\n */\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Account::class,\n fileName: (string) $crmData->id,\n avatarText: $name,\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Account */\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {\n $this->importOpportunity($pdOpportunity);\n $syncCount++;\n }\n }\n\n $this->logger->info('[Pipedrive] Sync Opportunities completed', [\n 'team' => $this->team->getId(),\n 'syncCount' => $syncCount,\n ]);\n } catch (Exception $exception) {\n $this->logger->info('[Pipedrive] Failed to sync Opportunities ', [\n 'team' => $this->team->getId(),\n 'params' => $parameters,\n 'strategy' => $strategy,\n 'reason' => $exception->getMessage(),\n 'syncedBeforeFailure' => $syncCount,\n ]);\n }\n\n if ($syncCount > 1000) {\n $this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [\n 'team' => $this->team->getId(),\n 'total' => $syncCount,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = ['crm_id' => $crmId];\n\n try {\n $generator = $strategy->fetchOpportunities($parameters);\n $pdOpportunity = $generator->current();\n } catch (ItemNotFoundException | PipedriveException $e) {\n $this->logger->info('[Pipedrive] Failed to sync opportunity', [\n 'crm_id' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n return $this->importOpportunity($pdOpportunity);\n }\n\n /**\n * @inheritdoc\n */\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData->deleted) {\n return null;\n }\n\n if ($crmData->org_id) {\n $orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n $account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($orgId);\n\n if ($account === null) {\n // For some bizarre reason, the org_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);\n\n return null;\n }\n }\n } elseif ($crmData->person_id) {\n // Try to get the organization from the person.\n $personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;\n $contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();\n\n if ($contact === null || $contact->account_id === null) {\n $contact = $this->syncContact($personId);\n\n if ($contact === null) {\n // For some bizarre reason, the person_id is not importable from Pipedrive- bail.\n $this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);\n\n return null;\n }\n\n if ($contact->account_id === null) {\n $this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());\n\n return null;\n }\n }\n\n $account = $contact->account;\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $crmData->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $crmData->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n\n $closeDate = null;\n if ($crmData->expected_close_date) {\n $closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');\n }\n\n $remotelyCreatedAt = Carbon::parse($crmData->add_time);\n\n $data = [\n 'team_id' => $this->team?->getId(),\n 'account_id' => $account?->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->title, 0, 128),\n 'value' => $crmData->value,\n 'currency_code' => CurrencyFormatter::formatCode($crmData->currency),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData->close_time !== null,\n 'is_won' => $crmData->won_time !== null,\n 'stage_id' => $stage?->getId(),\n 'record_type_id' => $recordType?->getId(),\n 'remotely_created_at' => $remotelyCreatedAt,\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $pdContacts = $this->client->getInstance()->persons()->all([\n 'limit' => 500,\n 'sort' => 'update_time DESC',\n ]);\n\n if ($pdContacts->getData() === null) {\n return 0;\n }\n\n foreach ($pdContacts->getData() as $pdContact) {\n // Only sync if previously imported.\n if ($this->hasContact($pdContact->id)) {\n $this->importContact($pdContact);\n $syncCount++;\n }\n }\n } catch (Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $pdContact = $this->client->getInstance()->persons()->find($crmId);\n } catch (ItemNotFoundException | PipedriveException $e) {\n throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);\n }\n\n return $this->importContact($pdContact->getData());\n }\n\n private function importContact($crmData): Contact\n {\n $photoPath = null;\n $account = null;\n if ($crmData->org_id) {\n /**\n * Pipedrive API is inconsistent, it may return a string variable, or an object\n */\n $crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;\n\n $account = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmProviderId)\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmProviderId);\n $photoPath = $this->teamService->generateAvatar(\n $crmData->id,\n $crmData->name,\n );\n } else {\n $photoPath = $account->photo_path;\n }\n }\n\n if ($photoPath === null) {\n $photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: (string) $crmData->id,\n modelType: Contact::class,\n fileName: (string) $crmData->id,\n avatarText: $crmData->name,\n );\n }\n\n $ownerId = $profile = null;\n if ($crmData->owner_id) {\n $ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();\n }\n\n $parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);\n\n $mobileNumber = null;\n if (isset($crmData->phone[1])) {\n $mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);\n }\n\n $email = null;\n if (isset($crmData->email[0]->value)) {\n $email = mb_strimwidth($crmData->email[0]->value, 0, 191);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => mb_strimwidth($crmData->name ?? '', 0, 100),\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobileNumber ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData->job_title ?? null,\n 'photo_path' => $photoPath,\n 'remotely_created_at' => Carbon::parse($crmData->add_time),\n ];\n\n /** @var Contact */\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n // Not applicable.\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?\\Jiminny\\Models\\Crm\\Profile\n {\n // Not needed yet.\n return null;\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);\n\n /*\n // If they have changed, raise a notification to the owner.\n $team->owner->notify(\n new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)\n );\n */\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (Exception $exception) {\n Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {\n $data = [];\n $params = [\n 'term' => $name,\n 'limit' => $count,\n 'start' => $offset,\n 'item_types' => 'person,organization',\n ];\n\n $objects = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $objects = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n if ($exception->getMessage() === 'Invalid token: access token is invalid') {\n throw new SocialAccountTokenInvalidException($exception->getMessage());\n }\n\n throw $exception;\n }\n\n if (empty($objects['items'])) {\n return [];\n }\n\n // Build mapped list.\n foreach ($objects['items'] as $object) {\n $object = $object['item'];\n\n // We only support these object types today.\n if (\\in_array($object['type'], ['person', 'organization']) === false) {\n continue;\n }\n\n $objectType = $object['type'] === 'person' ? 'contact' : 'account';\n $record = [\n 'crmId' => $object['id'],\n 'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),\n 'name' => $object['name'],\n 'industry' => null,\n 'title' => null,\n 'prospectType' => $objectType,\n 'phoneNumbers' => [],\n ];\n\n if (isset($object['organization']['name'])) {\n $record['organization'] = $object['organization']['name'];\n }\n\n if (isset($object['phones'][0])) {\n $parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);\n\n // Add phone number to record.\n if (empty($parsedNumber['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national(null, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n }\n\n $data[] = $record;\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'only_primary_association' => 1,\n 'status' => 'open',\n 'sort' => 'update_time DESC',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = 'add_time DESC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = 'add_time ASC';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = 'update_time DESC';\n $params['status'] = 'all_not_deleted';\n }\n\n $pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n if ($pdOpportunities === null) {\n return [];\n }\n\n foreach ($pdOpportunities as $pdOpportunity) {\n // Stage and RecordType are part of BusinessProcess\n $businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);\n if ($businessProcess === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n }\n\n $stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);\n if ($businessProcess !== null && $stage === null) {\n $stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);\n }\n\n /** @var ?RecordType $recordType */\n $recordType = $businessProcess?->recordTypes()->first();\n if ($businessProcess !== null && $recordType === null) {\n $businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);\n $recordType = $businessProcess?->recordTypes()->first();\n }\n\n $record = [\n 'crmId' => $pdOpportunity->id,\n 'name' => $pdOpportunity->title,\n 'value' => $pdOpportunity->formatted_value,\n 'won' => $pdOpportunity->won_time !== null,\n 'closed' => $pdOpportunity->status !== 'open',\n 'stage' => [\n 'id' => $stage?->id_string ?? '',\n 'name' => $stage?->name ?? '',\n ],\n 'recordType' => [\n 'id' => $recordType?->id_string ?? '',\n 'name' => $recordType?->name ?? '',\n ],\n ];\n\n if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n $pdActivities = null;\n $filters = ['done' => 0];\n switch ($objectType) {\n case 'contact':\n $pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();\n\n break;\n case 'account':\n // Prioritize looking up activities on the deal (which should be linked on the account anyway).\n if ($opportunityId) {\n $pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();\n }\n\n // If no deal activity, fall back to the organization.\n if ($pdActivities === null) {\n $pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();\n }\n\n break;\n }\n\n if ($pdActivities === null) {\n return [];\n }\n\n foreach ($pdActivities as $pdActivity) {\n // Only import active, scheduled tasks in the future.\n if ($pdActivity->active_flag) {\n $due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');\n $data[] = [\n 'crmId' => $pdActivity->id,\n 'subject' => $pdActivity->subject,\n 'due' => Carbon::parse($due)->toIso8601String(),\n 'type' => $pdActivity->type,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $email,\n 'item_types' => 'person',\n 'fields' => 'email',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $exception) {\n $this->logger->info('[Pipedrive] Email match failed', [\n 'email' => $email,\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if (\n ! $contact instanceof Contact\n && ! $account instanceof Account\n ) {\n return null;\n }\n\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n if (count($pdOpportunities) > 0) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember !== false) {\n return null;\n }\n\n $params = [\n 'term' => $phone,\n 'item_types' => 'person,organization',\n 'fields' => 'phone',\n ];\n\n $searchResult = [];\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $searchResult = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {\n return null;\n }\n\n $contact = $this->syncContact($searchResult['items'][0]['item']['id']);\n $account = $contact->account;\n\n $countryCode = $this->getCountryCode($contact, $account);\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function getCountryCode($contact, $account): ?string\n {\n if ($contact && $contact->country_code) {\n return $contact->country_code;\n } elseif ($account && $account->country_code) {\n return $account->country_code;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {\n $contact = null;\n $account = null;\n\n $params = [\n 'term' => $name,\n 'item_types' => 'person',\n 'fields' => 'name',\n ];\n\n $pdContact = null;\n\n try {\n if (! $this->client instanceof Client) {\n throw new \\InvalidArgumentException('Expected Pipedrive Client instance');\n }\n $response = $this->client->searchItems($params);\n $pdContact = $response['data'] ?? null;\n } catch (PipedriveApiException $e) {\n $this->logger->info('[Pipedrive] Name match failed', [\n 'name' => $name,\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {\n $contact = $this->syncContact($pdContact['items'][0]['item']['id']);\n $account = $contact->account;\n }\n\n if ($contact || $account) {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $pdOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId,\n );\n } catch (Exception $e) {\n $pdOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($pdOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n return false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @inheritdoc\n */\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'person_id' => $activity->hasContact() ? $activity->getContact()->getCrmProviderId() : null,\n 'org_id' => $activity->hasAccount() ? $activity->getAccount()->getCrmProviderId() : null,\n 'deal_id' => $activity->hasOpportunity() ? $activity->getOpportunity()->getCrmProviderId() : null,\n ];\n }\n\n private function buildCallPayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->scheduled_start_time->format('H:i'),\n 'due_date' => $activity->scheduled_start_time->toDateString(),\n 'duration' => gmdate('H:i', $activity->duration),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->fetchCustomFieldData($activity, Field::OBJECT_TASK)\n + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n $type = $this->getCrmType($activity->category);\n if ($type === null) {\n throw new Exception('No mapped CRM type in Pipedrive for \"' . $activity->category->name . '\"');\n }\n\n $data = [\n 'done' => 1,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_time' => $activity->created_at->format('H:i'),\n 'due_date' => $activity->created_at->toDateString(),\n 'type' => $type->value,\n 'subject' => $this->generateActivityTitle($activity),\n 'note' => $this->generateActivityDescription($activity),\n ] + $this->convertActivityAssociations($activity);\n\n return $this->upsertActivity($activity, $data);\n }\n\n private function upsertActivity(Activity $activity, array $data): Activity\n {\n // The activity should be logged under an existing activity.\n if ($activity->hasCrmProviderId()) {\n $existingActivity = $this->client->getActivity($activity->getCrmProviderId());\n\n if ($existingActivity && $existingData = $existingActivity->getData()) {\n $existingData = (array) $existingData;\n $data = $this->updateDescription($existingData, $data);\n $data = $this->updateProspectData($existingData, $data);\n\n // Just update the existing engagement with any fresh details.\n $this->client->updateActivity($activity->getCrmProviderId(), $data);\n }\n } else {\n $pdActivity = $this->client->createActivity($data);\n\n $activity->crm_provider_id = $pdActivity->getData()->id;\n $activity->save();\n }\n\n return $activity;\n }\n\n private function updateDescription(array $crmActivityData, array $payloadData): array\n {\n $crmActivityNote = $crmActivityData['note'] ?? null;\n\n if (! empty($crmActivityNote)) {\n if (! str_contains($crmActivityNote, self::CALL_HEADER)) {\n $payloadData['note'] = $crmActivityNote . \"\\n\\n\" . $payloadData['note'];\n } else {\n $payloadData['note'] = $crmActivityNote;\n }\n }\n\n return $payloadData;\n }\n\n private function updateProspectData($crmActivityData, array $data): array\n {\n $changedData = [];\n if ($crmActivityData['person_id'] && ! isset($data['person_id'])) {\n $changedData['person_id'] = $crmActivityData['person_id'];\n $data['person_id'] = $crmActivityData['person_id'];\n $data['org_id'] = null;\n $data['deal_id'] = null;\n } elseif (isset($data['person_id']) && $data['person_id'] != $crmActivityData['person_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in person_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['person_id'],\n 'crm_activity_data' => $crmActivityData['person_id'],\n ]);\n }\n\n if ($crmActivityData['org_id'] && ! isset($data['org_id'])) {\n $changedData['org_id'] = $crmActivityData['org_id'];\n $data['org_id'] = $crmActivityData['org_id'];\n $data['deal_id'] = null;\n } elseif (isset($data['org_id']) && $data['org_id'] != $crmActivityData['org_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in org_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['org_id'],\n 'crm_activity_data' => $crmActivityData['org_id'],\n ]);\n }\n\n if ($crmActivityData['deal_id'] && ! isset($data['deal_id'])) {\n $changedData['deal_id'] = $crmActivityData['deal_id'];\n $data['deal_id'] = $crmActivityData['deal_id'];\n } elseif (isset($data['deal_id']) && $data['deal_id'] != $crmActivityData['deal_id']) {\n $this->logger->info('[Pipedrive] Prospect conflict in deal_id', [\n 'activity_id' => $crmActivityData['id'],\n 'local_data' => $data['deal_id'],\n 'crm_activity_data' => $crmActivityData['deal_id'],\n ]);\n }\n\n if (! empty($changedData)) {\n $this->logger->info('[Pipedrive] Updated activity associations', $changedData);\n }\n\n return $data;\n }\n\n private function generateActivityTitle(Activity $activity): string\n {\n if ($activity->hasTitle()) {\n $title = $activity->title;\n } elseif ($activity->playbook_category_id) {\n $title = $activity->category->name;\n } else {\n $title = 'Conference Call';\n }\n\n return $title;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n self::CALL_HEADER\n );\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->hasTitle()) {\n // Insert the activity type since there is no native field.\n $description .= sprintf(\n '<p><strong><span style=\"font-size: 18.6667px; line-height: 22.4px;\">%s</span></strong></p>',\n $activity->category->name,\n );\n }\n\n if ($activity->isTypeSoftPhone()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound()) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">Review in Jiminny</a>'\n . ' ▶️'\n . '</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->type === Activity::TYPE_CONFERENCE) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity type field.\n if (empty($fields['type'])) {\n return null;\n }\n\n if (empty($fields['subject'])) {\n // We need to convert the name correctly.\n $playbook = $this->getPlaybook($activity->getUser());\n $type = $playbook->activityField->values()->where('value', $fields['type'])->first();\n $subject = ($type->label ?? $fields['type']) . ' with ' . $activity->prospect_name;\n } else {\n $subject = $fields['subject'];\n }\n\n $data = [\n 'done' => 0,\n 'user_id' => $this->profile->crm_provider_id,\n 'due_date' => $fields['due_date'] ?? date('Y-m-d'),\n 'due_time' => $fields['due_time'] ?? null,\n 'subject' => $subject,\n 'type' => $fields['type'],\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->activities()->add($data);\n\n // We don't actually create a corresponding activity object on our side yet.\n return $pdActivity->getData()->id;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, self::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'content' => $transcripts,\n ] + $this->convertActivityAssociations($activity);\n\n $pdActivity = $this->client->getInstance()->notes()->add($data);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $pdActivity->getData()->id;\n $transcription->save();\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->convertObjectTypeToResource($objectType)->update($objectId, $data);\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n $record = $this->convertObjectTypeToResource($objectType)->find($objectId)->getData();\n\n // We could map the fields requested here before returning.\n return $record ? (array) $record : [];\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case parent::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals();\n\n case parent::OBJECT_CONTACT:\n return $this->client->getInstance()->persons();\n\n case parent::OBJECT_ACCOUNT:\n return $this->client->getInstance()->organizations();\n\n case parent::OBJECT_TASK:\n return $this->client->getInstance()->activities();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \".$objectType.\"');\n }\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, [\n 'stage_id' => $stage->crm_provider_id,\n ]);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n $data->field->crm_provider_id => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n switch ($objectType) {\n case 'account':\n $url = $this->config->crm_base_url . '/organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $this->config->crm_base_url . '/person/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $this->config->crm_base_url . '/deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Pipedrive UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n public function importPipeline(int $pipelineId): ?BusinessProcess\n {\n try {\n $pipeline = $this->client->getInstance()->pipelines()->find($pipelineId)->getData();\n } catch (ItemNotFoundException $exception) {\n return null;\n }\n\n if ($pipeline === null) {\n return null;\n }\n\n return $this->importPipelineData($pipeline);\n }\n\n private function importPipelineData(mixed $pipeline): BusinessProcess\n {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $pipeline->active,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline->name, 0, 150),\n 'is_selectable' => $pipeline->active,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n return $businessProcess;\n }\n\n private function importStagesForBusinessProcess(BusinessProcess $businessProcess, ?string $missingId): ?Stage\n {\n $missingStage = null;\n $stages = [];\n $dealStages = $this->client->getInstance()\n ->stages()\n ->all(['pipeline_id' => (int) $businessProcess->crm_provider_id])\n ->getData();\n\n foreach ($dealStages as $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->importStage($dealStage);\n\n if ($missingId !== null && $stage->crm_provider_id == $missingId) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n\n return $missingStage;\n }\n\n private function importStage(mixed $dealStage): Stage\n {\n return $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage->id,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage->name, 0, 50),\n 'label' => mb_strimwidth($dealStage->name, 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $dealStage->order_nr,\n 'is_selectable' => $dealStage->active_flag,\n 'probability' => $dealStage->deal_probability,\n ]);\n }\n\n private function getBusinessProcesses(string $pipelineId): ?BusinessProcess\n {\n return $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $pipelineId)\n ->first();\n }\n\n private function getStage(?BusinessProcess $businessProcess, string $stageId): ?Stage\n {\n return $businessProcess\n ?->stages()\n ->where('crm_provider_id', $stageId)\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if (! is_numeric($crmProviderId)) {\n $this->logger->warning('[Pipedrive] Invalid activity ID format', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n $activity = $this->client->getActivity($crmProviderId);\n\n return ($activity->active_flag ?? false) === true;\n } catch (HttpNotFoundException) {\n // Activity not found in CRM - this is expected and permanent\n $this->logger->info('[Pipedrive] Activity not found during verification', [\n 'activity_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
3865544371963712397
|
-7980155751442543530
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
5
119
3
9
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Pipedrive;
use Carbon\Carbon;
use Devio\Pipedrive\Exceptions\ItemNotFoundException;
use Devio\Pipedrive\Exceptions\PipedriveException;
use Exception;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\PipedriveInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Events\Users\SocialAccountDisconnected;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\SocialAccountTokenInvalidException;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Log;
use UnexpectedValueException;
class Service extends BaseService implements
PipedriveInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string CALL_HEADER = 'Jiminny Summary';
/**
* @var ClientInterface|Client
*/
protected $client;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(Client $client, private readonly ProspectPhotoPathService $prospectPhotoPathService)
{
parent::__construct();
$this->client = $client;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Pipedrive';
}
/**
* @inheritdoc
*/
public function setUser(User $user): void
{
try {
parent::setUser($user);
} catch (InvalidArgumentException $exception) {
// In Pipedrive's case the OAuth client isn't setup to catch the failure properly. We handle this manually.
if ($this->client->oauthAccount->state !== SocialAccount::STATE_FULL_REFRESH_REQUIRED &&
$exception->getMessage() === 'Required option not passed: "access_token"') {
// Something terrible happened to their token, they need to reconnect.
$this->client->oauthAccount->update(['state' => SocialAccount::STATE_FULL_REFRESH_REQUIRED]);
event(new SocialAccountDisconnected($this->client->oauthAccount));
}
throw new SocialAccountTokenInvalidException('Cannot refresh token. Full refresh required.');
}
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_PIPEDRIVE);
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
switch ($fieldType) {
case Field::TYPE_DATE:
$value = $internal ? Carbon::parse($fieldValue) : $fieldValue;
break;
default:
$value = $fieldValue;
}
return $value;
}
/**
* Gets the valid fields for a given Object via the property APIs.
*
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
switch ($crmObject) {
case 'task':
$properties = $this->client->getInstance()->activityFields();
break;
case 'account':
$properties = $this->client->getInstance()->organizationFields();
break;
case 'contact':
$properties = $this->client->getInstance()->personFields();
break;
case 'opportunity':
$properties = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException();
}
$fields = [];
try {
$response = $properties->all();
if ($response->isSuccess() === false) {
throw new Exception($response->getContent(), $response->getStatusCode());
}
foreach ($response->getData() as $property) {
$fields[] = ['label' => $property->name, 'name' => $property->key];
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
return;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
$field->description = null;
$field->label = mb_strimwidth($crmField->name, 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($crmField->field_type);
$field->is_selectable = $crmField->active_flag;
$field->save();
}
}
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'enum':
case 'stage':
case 'status':
return Field::TYPE_PICKLIST;
case 'varchar':
return Field::TYPE_TEXT;
case 'int':
case 'double':
return Field::TYPE_NUMBER;
case 'text':
return Field::TYPE_TEXTAREA;
case 'monetary':
return Field::TYPE_CURRENCY;
case Field::TYPE_DATE:
case Field::TYPE_TIME:
case Field::TYPE_PHONE:
return $fieldType;
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
switch ($field->object_type) {
case Field::OBJECT_TASK:
$crmFields = $this->client->getInstance()->activityFields();
break;
case Field::OBJECT_ACCOUNT:
$crmFields = $this->client->getInstance()->organizationFields();
break;
case Field::OBJECT_CONTACT:
$crmFields = $this->client->getInstance()->personFields();
break;
case Field::OBJECT_OPPORTUNITY:
$crmFields = $this->client->getInstance()->dealFields();
break;
default:
throw new InvalidArgumentException('Invalid field type "' . $field->object_type . '" for field ' . $field->id . '.');
}
if ($field->crm_provider_id == 'stage_id') {
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$dealStages = $this->client->getInstance()->stages()->all(['pipeline_id' => $pipeline->id])->getData();
foreach ($dealStages as $i => $dealStage) {
$values = [
'value' => $dealStage->id,
'label' => $dealStage->name,
'sequence' => $i,
];
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $dealStage->id,
], $values);
}
}
return $fieldValues;
}
// Sadly we must traverse the entire list because they don't allow to get an individual field by key.
foreach ($crmFields->all()->getData() as $crmField) {
if ($crmField->key === $field->crm_provider_id) {
// Import all active values.
if (property_exists($crmField, 'options')) {
foreach ($crmField->options as $i => $option) {
$values[] = [
'value' => $option->id,
'label' => $option->label,
'sequence' => $i,
];
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
return $fieldValues;
}
/**
* @inheritdoc
*
* @throws SocialAccountTokenInvalidException
* @throws PipedriveException
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// We create a business process to contain the pipeline, and later store all stages against it.
$pipelines = $this->client->getInstance()->pipelines()->all()->getData();
foreach ($pipelines as $pipeline) {
$businessProcess = $this->importPipelineData($pipeline);
$stage = $this->importStagesForBusinessProcess($businessProcess, $missingStageName);
if ($missingStageName !== null && $stage?->crm_provider_id == $missingStageName) {
$missingStage = $stage;
}
}
} catch (PipedriveException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
// Pipedrive doesn't use leads.
return 0;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
// Pipedrive doesn't use leads.
return null;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdAccounts = $this->client->getInstance()->organizations()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdAccounts->getData() === null) {
return 0;
}
foreach ($pdAccounts->getData() as $pdAccount) {
// Only sync if previously imported.
if ($this->hasAccount($pdAccount->id)) {
$this->importAccount($pdAccount);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
try {
$hsAccount = $this->client->getInstance()->organizations()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the company due to an external error.', $e->getCode(), $e);
}
return $this->importAccount($hsAccount->getData());
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = $crmData->country_code;
if ($countryCode === null && $crmData->address_country) {
$countryCode = $this->convertCountryNameToCode($crmData->address_country);
}
$name = $crmData->name;
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
/**
* Pipedrive API point is inconsistent. Sometimes it delivers an object, sometimes it delivers an integer ID.
* These are real samples from API results:
* { ... owner_id: 23696001, ...}
* OR
* {
* ...
* owner_id: {
* active_flag: false,
* id: 12972717,
* name: 'name here',
* value: 12972717
* }
* }
*/
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->id : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Account::class,
fileName: (string) $crmData->id,
avatarText: $name,
),
'country_code' => $countryCode,
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Account */
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $pdOpportunity) {
$this->importOpportunity($pdOpportunity);
$syncCount++;
}
}
$this->logger->info('[Pipedrive] Sync Opportunities completed', [
'team' => $this->team->getId(),
'syncCount' => $syncCount,
]);
} catch (Exception $exception) {
$this->logger->info('[Pipedrive] Failed to sync Opportunities ', [
'team' => $this->team->getId(),
'params' => $parameters,
'strategy' => $strategy,
'reason' => $exception->getMessage(),
'syncedBeforeFailure' => $syncCount,
]);
}
if ($syncCount > 1000) {
$this->logger->info('[Pipedrive] Sync Opportunities - count warning ', [
'team' => $this->team->getId(),
'total' => $syncCount,
]);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = ['crm_id' => $crmId];
try {
$generator = $strategy->fetchOpportunities($parameters);
$pdOpportunity = $generator->current();
} catch (ItemNotFoundException | PipedriveException $e) {
$this->logger->info('[Pipedrive] Failed to sync opportunity', [
'crm_id' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
return $this->importOpportunity($pdOpportunity);
}
/**
* @inheritdoc
*/
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData->deleted) {
return null;
}
if ($crmData->org_id) {
$orgId = is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config->accounts()->where('crm_provider_id', (string) $orgId)->first();
if ($account === null) {
$account = $this->syncAccount($orgId);
if ($account === null) {
// For some bizarre reason, the org_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Account could not be imported ' . $orgId);
return null;
}
}
} elseif ($crmData->person_id) {
// Try to get the organization from the person.
$personId = is_object($crmData->person_id) ? $crmData->person_id->value : $crmData->person_id;
$contact = $this->config->contacts()->where('crm_provider_id', (string) $personId)->first();
if ($contact === null || $contact->account_id === null) {
$contact = $this->syncContact($personId);
if ($contact === null) {
// For some bizarre reason, the person_id is not importable from Pipedrive- bail.
$this->logger->info('[Pipedrive] Contact could not be imported ' . $personId);
return null;
}
if ($contact->account_id === null) {
$this->logger->info('[Pipedrive] No account associated with contact ' . $contact->getId());
return null;
}
}
$account = $contact->account;
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $crmData->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $crmData->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $crmData->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $crmData->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$ownerId = is_object($crmData->user_id) ? $crmData->user_id->value : $crmData->user_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
$closeDate = null;
if ($crmData->expected_close_date) {
$closeDate = Carbon::parse($crmData->expected_close_date)->format('Y-m-d');
}
$remotelyCreatedAt = Carbon::parse($crmData->add_time);
$data = [
'team_id' => $this->team?->getId(),
'account_id' => $account?->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->title, 0, 128),
'value' => $crmData->value,
'currency_code' => CurrencyFormatter::formatCode($crmData->currency),
'close_date' => $closeDate,
'is_closed' => $crmData->close_time !== null,
'is_won' => $crmData->won_time !== null,
'stage_id' => $stage?->getId(),
'record_type_id' => $recordType?->getId(),
'remotely_created_at' => $remotelyCreatedAt,
];
/** @var Opportunity $opportunity */
$opportunity = $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
// import external fields into crm_field_data if present
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData((array) $crmData, $crmFields, $opportunity->getId());
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$pdContacts = $this->client->getInstance()->persons()->all([
'limit' => 500,
'sort' => 'update_time DESC',
]);
if ($pdContacts->getData() === null) {
return 0;
}
foreach ($pdContacts->getData() as $pdContact) {
// Only sync if previously imported.
if ($this->hasContact($pdContact->id)) {
$this->importContact($pdContact);
$syncCount++;
}
}
} catch (Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
try {
$pdContact = $this->client->getInstance()->persons()->find($crmId);
} catch (ItemNotFoundException | PipedriveException $e) {
throw new CrmException('Could not sync the contact due to an external error.', $e->getCode(), $e);
}
return $this->importContact($pdContact->getData());
}
private function importContact($crmData): Contact
{
$photoPath = null;
$account = null;
if ($crmData->org_id) {
/**
* Pipedrive API is inconsistent, it may return a string variable, or an object
*/
$crmProviderId = (string) is_object($crmData->org_id) ? $crmData->org_id->value : $crmData->org_id;
$account = $this->config
->accounts()
->where('crm_provider_id', $crmProviderId)
->first();
if ($account === null) {
$account = $this->syncAccount($crmProviderId);
$photoPath = $this->teamService->generateAvatar(
$crmData->id,
$crmData->name,
);
} else {
$photoPath = $account->photo_path;
}
}
if ($photoPath === null) {
$photoPath = $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: (string) $crmData->id,
modelType: Contact::class,
fileName: (string) $crmData->id,
avatarText: $crmData->name,
);
}
$ownerId = $profile = null;
if ($crmData->owner_id) {
$ownerId = is_object($crmData->owner_id) ? $crmData->owner_id->value : $crmData->owner_id;
$profile = $this->config->profiles()->where('crm_provider_id', (string) $ownerId)->first();
}
$parsedNumber = $this->buildContactPhone(null, $crmData->phone[0]->value);
$mobileNumber = null;
if (isset($crmData->phone[1])) {
$mobileNumber = $this->buildContactMobilePhone(null, $crmData->phone[1]->value);
}
$email = null;
if (isset($crmData->email[0]->value)) {
$email = mb_strimwidth($crmData->email[0]->value, 0, 191);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => mb_strimwidth($crmData->name ?? '', 0, 100),
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobileNumber ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData->job_title ?? null,
'photo_path' => $photoPath,
'remotely_created_at' => Carbon::parse($crmData->add_time),
];
/** @var Contact */
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData->id], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
// Not applicable.
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?\Jiminny\Models\Crm\Profile
{
// Not needed yet.
return null;
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType)),
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
Log::debug(ucfirst($fieldType) . ' fields changed from ' . $this->profile->{$fieldType . '_fields'} . ' to: ' . $fields);
/*
// If they have changed, raise a notification to the owner.
$team->owner->notify(
new SyncedFieldsChanged($fieldType, $profile->getFieldsAsArray($fieldType), $newFields)
);
*/
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (Exception $exception) {
Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count, $offset) {
$data = [];
$params = [
'term' => $name,
'limit' => $count,
'start' => $offset,
'item_types' => 'person,organization',
];
$objects = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$objects = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
if ($exception->getMessage() === 'Invalid token: access token is invalid') {
throw new SocialAccountTokenInvalidException($exception->getMessage());
}
throw $exception;
}
if (empty($objects['items'])) {
return [];
}
// Build mapped list.
foreach ($objects['items'] as $object) {
$object = $object['item'];
// We only support these object types today.
if (\in_array($object['type'], ['person', 'organization']) === false) {
continue;
}
$objectType = $object['type'] === 'person' ? 'contact' : 'account';
$record = [
'crmId' => $object['id'],
'crmUrl' => $this->generateProviderUrl($object['id'], $objectType),
'name' => $object['name'],
'industry' => null,
'title' => null,
'prospectType' => $objectType,
'phoneNumbers' => [],
];
if (isset($object['organization']['name'])) {
$record['organization'] = $object['organization']['name'];
}
if (isset($object['phones'][0])) {
$parsedNumber = $this->buildContactPhone(null, $object['phones'][0]);
// Add phone number to record.
if (empty($parsedNumber['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $parsedNumber['phone'],
'nationalFormat' => phone_national(null, $parsedNumber['phone']),
'type' => 'phone',
];
}
}
$data[] = $record;
}
return $data;
});
return $data;
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'only_primary_association' => 1,
'status' => 'open',
'sort' => 'update_time DESC',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = 'add_time DESC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = 'add_time ASC';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = 'update_time DESC';
$params['status'] = 'all_not_deleted';
}
$pdOpportunities = $this->client->getInstance()->organizations()->deals($account->crm_provider_id, $params)->getData();
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
if ($pdOpportunities === null) {
return [];
}
foreach ($pdOpportunities as $pdOpportunity) {
// Stage and RecordType are part of BusinessProcess
$businessProcess = $this->getBusinessProcesses((string) $pdOpportunity->pipeline_id);
if ($businessProcess === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
}
$stage = $this->getStage($businessProcess, (string) $pdOpportunity->stage_id);
if ($businessProcess !== null && $stage === null) {
$stage = $this->importStagesForBusinessProcess($businessProcess, (string) $pdOpportunity->stage_id);
}
/** @var ?RecordType $recordType */
$recordType = $businessProcess?->recordTypes()->first();
if ($businessProcess !== null && $recordType === null) {
$businessProcess = $this->importPipeline((int) $pdOpportunity->pipeline_id);
$recordType = $businessProcess?->recordTypes()->first();
}
$record = [
'crmId' => $pdOpportunity->id,
'name' => $pdOpportunity->title,
'value' => $pdOpportunity->formatted_value,
'won' => $pdOpportunity->won_time !== null,
'closed' => $pdOpportunity->status !== 'open',
'stage' => [
'id' => $stage?->id_string ?? '',
'name' => $stage?->name ?? '',
],
'recordType' => [
'id' => $recordType?->id_string ?? '',
'name' => $recordType?->name ?? '',
],
];
if ($ownerId && isset($pdOpportunity->user_id->id) && $pdOpportunity->user_id->id === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
$pdActivities = null;
$filters = ['done' => 0];
switch ($objectType) {
case 'contact':
$pdActivities = $this->client->getInstance()->persons()->activities($objectId, $filters)->getData();
break;
case 'account':
// Prioritize looking up activities on the deal (which should be linked on the account anyway).
if ($opportunityId) {
$pdActivities = $this->client->getInstance()->deals()->activities($opportunityId, $filters)->getData();
}
// If no deal activity, fall back to the organization.
if ($pdActivities === null) {
$pdActivities = $this->client->getInstance()->organizations()->activities($objectId, $filters)->getData();
}
break;
}
if ($pdActivities === null) {
return [];
}
foreach ($pdActivities as $pdActivity) {
// Only import active, scheduled tasks in the future.
if ($pdActivity->active_flag) {
$due = $pdActivity->due_date . ($pdActivity->due_time ? ' ' . $pdActivity->due_time . ':00' : '');
$data[] = [
'crmId' => $pdActivity->id,
'subject' => $pdActivity->subject,
'due' => Carbon::parse($due)->toIso8601String(),
'type' => $pdActivity->type,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contact = null;
$account = null;
$params = [
'term' => $email,
'item_types' => 'person',
'fields' => 'email',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $exception) {
$this->logger->info('[Pipedrive] Email match failed', [
'email' => $email,
'reason' => $exception->getMessage(),
]);
return null;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if (
! $contact instanceof Contact
&& ! $account instanceof Account
) {
return null;
}
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (count($pdOpportunities) > 0) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
// Check if the user is internal.
$teamMember = $this->team->users()->where('phone', $phone)->exists();
// Skip the attendee if internal.
if ($teamMember !== false) {
return null;
}
$params = [
'term' => $phone,
'item_types' => 'person,organization',
'fields' => 'phone',
];
$searchResult = [];
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$searchResult = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Phone match failed', [
'phone' => $phone,
'reason' => $e->getMessage(),
]);
return null;
}
if (empty($searchResult['items']) || count($searchResult['items']) !== 1) {
return null;
}
$contact = $this->syncContact($searchResult['items'][0]['item']['id']);
$account = $contact->account;
$countryCode = $this->getCountryCode($contact, $account);
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function getCountryCode($contact, $account): ?string
{
if ($contact && $contact->country_code) {
return $contact->country_code;
} elseif ($account && $account->country_code) {
return $account->country_code;
}
return null;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$result = Cache::remember($this->profile->id . $name, 60, function () use ($name, $userId) {
$contact = null;
$account = null;
$params = [
'term' => $name,
'item_types' => 'person',
'fields' => 'name',
];
$pdContact = null;
try {
if (! $this->client instanceof Client) {
throw new \InvalidArgumentException('Expected Pipedrive Client instance');
}
$response = $this->client->searchItems($params);
$pdContact = $response['data'] ?? null;
} catch (PipedriveApiException $e) {
$this->logger->info('[Pipedrive] Name match failed', [
'name' => $name,
'reason' => $e->getMessage(),
]);
return false;
}
if (! empty($pdContact['items']) && count($pdContact['items']) === 1) {
$contact = $this->syncContact($pdContact['items'][0]['item']['id']);
$account = $contact->account;
}
if ($contact || $account) {
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$pdOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId,
);
} catch (Exception $e) {
$pdOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($pdOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($pdOpportunities[0]['crmId']);
$stage = $opportunity?->stage;
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
return false;
});
return is_array($result) ? $result : null;
}
/**
* @inheritdoc
*/
public function saveActivity(Activity $activity): Activity
{
switch ($activity->type) {
case Activity::TYPE_CONFERENCE:
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
$activity = $this->buildCallPayload($activity);
break;
case Activity::TYPE_SMS_INBOUND:
case Activity::TYPE_SMS_OUTBOUND:
$activity = $this->buildTextMessagePayload($activity);
...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45289
|
1623
|
28
|
2026-05-14T14:29:17.560543+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768957560_m1.jpg...
|
PhpStorm
|
faVsco.js – ActivityPlaybookTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTestv100% С8• Thu 14 May 17:29:17QProject vReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php> D DummyUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpD Helpers• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.phpT ActivityPlaybookTrait.php© Arraylterator.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.php© PlainTextDecorateActivity.php( ConnectionStateTrait.phpT ActivityPlaybookTrait.php XCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18© CrmHelperRepository.php© FilterJoinedParticipants.php.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpT OpportunitySyncableFieldsTv Hubspot17D AccountSyncStrategy40> D Actions© HubspotPaginationService.php© HandleHubspotRateLimit.phptrait ActivityPlaybookTraitprotected function getPlaybookCategory(Playbook $playbook, string $categoryName): ?PlaybookCategory{…•}44D ContactSyncStrategy45public function matchesCrmType(PlaybookCategory$category): bool> DDTO46> D Fields47> D Journal48D Metadata49Splaybook = Scategory->getPLaybookO;if ($playbook === null) {return false;v OpportunitySyncStrategy50> [ Concerns51© HubspotLastModifiedByF52© HubspotLastModifiedCre53© HubspotLastModifiedCre54© HubspotLastModifiedOpe$activityField = $playbook->getActivityField();if ($activityField === null) {return false;55© HubspotLastModifiedSyn56© HubspotSingleSyncStrate57C HubspotSyncStrategyBa:58// Check the field values for a matching option.return $this->crmHelperRepository->existsActivityFieldValveByName($activityField, $category->getName());© HubspotWebhookBatchS59v D Pagination60© HubspotPaginationServic61public function getCrmType(?PlaybookCategory $category): ?FieldValue© PaginationConfig.php62© PaginationState.php63> D ProspectSearchStrategy64> O Redisif ($category === null) 1return null;65v D ServiceTraits+ OpportunitySyncTrait.phy6667$playbook = Scategory->getPlaybook:T SyncCrmEntities Trait.php() CunaCioldeTrait nhn68if ($playbookassnull) {Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=custom.log=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.Lid = 1052 andIMaccounts wheiactivities61:21UTF-8Co 4 spaces...
|
NULL
|
-2777881173078134395
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTestv100% С8• Thu 14 May 17:29:17QProject vReportController.php© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php> D DummyUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpD Helpers• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.phpT ActivityPlaybookTrait.php© Arraylterator.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.php© PlainTextDecorateActivity.php( ConnectionStateTrait.phpT ActivityPlaybookTrait.php XCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18© CrmHelperRepository.php© FilterJoinedParticipants.php.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpT OpportunitySyncableFieldsTv Hubspot17D AccountSyncStrategy40> D Actions© HubspotPaginationService.php© HandleHubspotRateLimit.phptrait ActivityPlaybookTraitprotected function getPlaybookCategory(Playbook $playbook, string $categoryName): ?PlaybookCategory{…•}44D ContactSyncStrategy45public function matchesCrmType(PlaybookCategory$category): bool> DDTO46> D Fields47> D Journal48D Metadata49Splaybook = Scategory->getPLaybookO;if ($playbook === null) {return false;v OpportunitySyncStrategy50> [ Concerns51© HubspotLastModifiedByF52© HubspotLastModifiedCre53© HubspotLastModifiedCre54© HubspotLastModifiedOpe$activityField = $playbook->getActivityField();if ($activityField === null) {return false;55© HubspotLastModifiedSyn56© HubspotSingleSyncStrate57C HubspotSyncStrategyBa:58// Check the field values for a matching option.return $this->crmHelperRepository->existsActivityFieldValveByName($activityField, $category->getName());© HubspotWebhookBatchS59v D Pagination60© HubspotPaginationServic61public function getCrmType(?PlaybookCategory $category): ?FieldValue© PaginationConfig.php62© PaginationState.php63> D ProspectSearchStrategy64> O Redisif ($category === null) 1return null;65v D ServiceTraits+ OpportunitySyncTrait.phy6667$playbook = Scategory->getPlaybook:T SyncCrmEntities Trait.php() CunaCioldeTrait nhn68if ($playbookassnull) {Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=custom.log=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]D V234Go jiminny0841A3 X4 A Vm migrations oim teams wherem crm_layouts !iM crm_layout_eiIM crm_fields Wim features;m team_feature:m opportunitie:m teams;.id, CASEWHENidFROMsocial.on u.id= sa.:1..n<->1: on t.Lid = 1052 andIMaccounts wheiactivities61:21UTF-8Co 4 spaces...
|
45288
|
NULL
|
NULL
|
NULL
|
|
45290
|
1624
|
18
|
2026-05-14T14:29:17.891378+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778768957891_m2.jpg...
|
PhpStorm
|
faVsco.js – ActivityPlaybookTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
2586234742233688171
|
-7051436856496256053
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeavev Q SearchDate ModifiedYesterdav at 13.35Yesterday at 13:35Yesterday at 13.34Yesterdav at 13:33Yesterday at 13:32Yesterdav at 13:37Yesterday at 13:31Yesterday at 13.30Yesterdav at 13:30Yesterday at 13:29resterday at 15.4gYesterdav at 13:28Yesterday at 13:28Yesterday at 13:27Yesterdav at 13:26resterday at 13-4oYesterdav at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Voctorday at 12:22Yesterday at 13.21Yesterdav at 13:20Yesterdav at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13:18Yesterday at 13.17Yecterdav at 12:17Yesterdav at 13:16Yesterday at 13-10Yesterdav at 13:15Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:12Yesterday at 13.12Yesterdav at 13:12Yesterday at 13:11Yesterday at 13:10Yoctorday at 12:10Yesterdav at 13:09Yesterday at 13.09Yocterdav at 12:081Yesterdav at 13:08Yesterdav at 13:071S K:MPEG-4 movie16 KB17 KB29 Kb6 KE12 KB9 KB7 K:MDEG-A movieMPEG-4 movieMPEG-4 movieMPE0"4 movie8 KBMDSG-A movie37 KB10 KbMP2G-4 movie7 KBI8 KBMPEG-4 movieMPEG-4 movie8 K:72 KB14 KE13 K:MoECh movioMPEG-4 movieO KRI18 KB12 KBMPEG-1 movidMPEG-4 movie10 KEMPEG-4 movie16 KB MPEG-4 movie6 KB6 KB1MPEG-4 movie12 KB23 KB8 KBMDSG.A movicMPEG-4 movie6KE6 KBMPEG-4 movieMPEG-4 movie11 KB11 K:MPEG-4 movie20 kRMDEC A movid10 KBMPEG-4 movie7 KPMDEG-A movie5 KBMPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KB88 KBMPEG-4 movieMDEC.A movialMPEG-4 movieKO KRMDEG-A movie98 KBMPEG-4 movie97 KBMPEG-4 movie66 K:MPEG-A movie44 KB MPEG-4 movie93 KB78 KB50 kpMPEG-4 movieMDEG.A movio58 KB27 KBMPEG-4 movie7KP12 KBMADECA movid32 KB17 K8MPEG-4 movieFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence hettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.53 GB availabld• Inu 14 May 1/.29.14Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45286
|
NULL
|
NULL
|
NULL
|