|
52869
|
1854
|
17
|
2026-05-18T11:20:30.036953+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103230036_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-943456739835505562
|
-8636494053633454656
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
SlackFileEditViewGoHistoryWindowHelpEU ()0 .DOCKERDOCKER (docker-compose)connections"}1 {"type" : "log"ticsearch""data"],"pid" :7,elasticsearch: 9200*}{"type" : "logasticsearch", "data"], "pid" :7,81DEV (docker)₴2@timestamp":"2026-05-18T11:20:21Z""tags" : ["error":"[ConnectionError]:getaddrinfo ENOTFOUND elasticse2026-05-18111:20:22Z'"tags" : ["warning"revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:22Z", "tags" : ["warning", "elconnections"}"2026-05-18T11:20:22Z""tags" : ["error", "plugmessage":"Failed to pollfor work: Error: Noconnections"}kibana{"type" : "log""@timestamp" : "2026-05-18T11:20:24Z" , "tags" : ["error", "elasticsearch","data"],"pid" :7,"message":"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch: 920^1docker_lamp_11212S DONEkibana{"t:4asticsearch""data"]PSh:9200/"}$Ikibanaasticsearch"{"t:"data"]kibanains"{"t), "taskManager"Living connections"}docker_lamp_1'/usr/local/bin/php'Firefox'artisan'meeting-bot: schedule-bot › '/proc/1/fd/1' 2>&1.kibana{"type" : "log""@timestamp": "2026-05-18T11:20:26Z""tags" : ["error""elasticsearch", "data"],"pid" :7, "message":"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200"}kibana1 {"type""@timestamp":"2026-05-18T11:20:28Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7,"message" : "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:28Z" , "tags" : ["warning" , "elasticsearch", "data"],"pid":7,"message"connections"}kibana"@timestamp""2026-05-18T11:20:28Z""tags" : ["error","plugins","taskManager""taskManager"], "pid":7,"message" : "Failed to pollfor work: Error: NoLiving connections"}kibana1 {"type":"log""@timestamp" : "2026-05-18T11:20:29Z", "tags" : ["error", "elasticsearch", "data"], "pid" :7message"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch: 9200"}View in Docker Desktop• View ConfigEnable WatchHomeDMsActivityED-Jiminny...Metrorrtence# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messagesSupport Daily • in 40m100% C8• Mon 18 May 14:20:29Describe what you are looking for# releases8 226 0•MessagesC Files• Bookmarks52848f50 - Sele-tinnlir* drop reference toToday ~TargetEntitie.:ES_CHUNK_SIZEf32fb682 - Update TargetEntitiesSelector touse ChunkSize instead of internal const.Update test8715e69d - Remove an unused import.36cе6е8c - Remove comments.Show morejiminny/app| Added by GitHubZd luuul Sidilidlo8. Mario Georgiev. Nikolay Ivanovdo James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y...AppsJira CloudToast31GitHub APP 2:12 PM3 new commits pushed to master bymihailmihaylovjiminnyeb6cfc4f - JY-20920: Fix participant matcherb5a8a4e0 - Merge branch 'master' into JY-20920-fix-participant-matcher231e9ad7 - Merge pull request #12091 fromjiminny/JY-20920-fix-participant-matcherjiminny/app| Added by GitHubMessage #releases+АаNew...
|
52867
|
NULL
|
NULL
|
NULL
|
|
52873
|
1854
|
20
|
2026-05-18T11:20:38.319709+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103238319_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82X t1DOCKER (docker-compose)connections"}1 {"type" : "log""@timestamp": "2026-05-18T11:20:29Z""tags" : ["error"ticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type": "log","@timestamp": "2026-05-18T11:20:31Z'tags": ["error"ticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}1 {"type": "log""@timestamp": "2026-05-18T11:20:31Z", "tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:31Z","tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibana1 {"type": "log", "@timestamp" : "2026-05-18T11:20:31Z", "tags" : ["error", "plugins""taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLivingconnections"}kibana1 {"type" : "log", "@timestamp" : "2026-05-18T11:20:34Z" , "tags" : ["error","elasticsearch",, "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}docker_lamp_1 |2026-05-18 11:20:26 Running ['artisan' dialers:monitor-activities] •8S DONEdocker_lamp_11/fd/1'1 l '/usr/local/bin/php' 'artisan' dialers:monitor-activities › */proc/2>&1kibana1 {"type":"log", "@timestamp" :"2026-05-18T11:20:34Z","tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:34Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No livingconnections"}kibana1 {"type": "log", "@timestamp" : "2026-05-18T11:20:34Z" , "tags" : ["error"ins", "taskManager", "taskManager"], "pid":7, "message": "Failed to pollfor work: Error: NoLiving connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:20:362""tags" : ["error", "elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type" : "log""@timestamp": "2026-05-18T11:20:37Z","tags" : ["warning"asticsearch", "data"], "pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:37Z", "tags" : ["error", "plugins", "taskManager",,"taskManager"],"pid" :7,"message": "Failed to poll for work: Error: NoLiving connections"}View in Docker Desktopo View ConfigEnable WatchHomeDMsActivityFilesLaterMore-Jiminny ...MetromrenCE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N. Mario GeorgievNikolay Ivanov4o James Graham *. Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 40 m100% <78• Mon 18 May 14:20:38Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today ~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] •Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started!G Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
2158587075487163474
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82X t1DOCKER (docker-compose)connections"}1 {"type" : "log""@timestamp": "2026-05-18T11:20:29Z""tags" : ["error"ticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type": "log","@timestamp": "2026-05-18T11:20:31Z'tags": ["error"ticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}1 {"type": "log""@timestamp": "2026-05-18T11:20:31Z", "tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:31Z","tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibana1 {"type": "log", "@timestamp" : "2026-05-18T11:20:31Z", "tags" : ["error", "plugins""taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLivingconnections"}kibana1 {"type" : "log", "@timestamp" : "2026-05-18T11:20:34Z" , "tags" : ["error","elasticsearch",, "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}docker_lamp_1 |2026-05-18 11:20:26 Running ['artisan' dialers:monitor-activities] •8S DONEdocker_lamp_11/fd/1'1 l '/usr/local/bin/php' 'artisan' dialers:monitor-activities › */proc/2>&1kibana1 {"type":"log", "@timestamp" :"2026-05-18T11:20:34Z","tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:34Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No livingconnections"}kibana1 {"type": "log", "@timestamp" : "2026-05-18T11:20:34Z" , "tags" : ["error"ins", "taskManager", "taskManager"], "pid":7, "message": "Failed to pollfor work: Error: NoLiving connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:20:362""tags" : ["error", "elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type" : "log""@timestamp": "2026-05-18T11:20:37Z","tags" : ["warning"asticsearch", "data"], "pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:37Z", "tags" : ["error", "plugins", "taskManager",,"taskManager"],"pid" :7,"message": "Failed to poll for work: Error: NoLiving connections"}View in Docker Desktopo View ConfigEnable WatchHomeDMsActivityFilesLaterMore-Jiminny ...MetromrenCE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N. Mario GeorgievNikolay Ivanov4o James Graham *. Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 40 m100% <78• Mon 18 May 14:20:38Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today ~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] •Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started!G Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52874
|
1855
|
23
|
2026-05-18T11:20:38.319705+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103238319_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormProiectFV faVsco.jsVIewINavigarecodeLarave PhpStormProiectFV faVsco.jsVIewINavigarecodeLaravelKeractor°9 master• laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]« console [PROD] X# console [euyDAvayom BaseServicem BloobirdsD CloseM CloudCalllCloudTalkM ConnectAndSell) M DemoDeck_ Dialpac• C EightByEighturiveNine•J Gmaiu GonoGooclemeerD GoToMeetingGrooveD HubSpotImportJiminnyawlustcalllM MiaratorM NatterboxOficeOrumOutreachlM PinaCentrallM PinaCentralViden1 SalecforceM7 SalecioftTm TeamsToludCActivityController.ong© SoftPhoneManager.php xfinal readonly class SoftPhoneManager implements ConferenceManagerprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\AA console [STAGING]M TwiliorlexM TwilinGlovDirostM TwilinVidenUploaderD Vonage• D Xant0 Zoom→_ZoomBot)ZoomPhoneC) ActivitvCrmFieldsResolver.ohoC) ActivitvLoaService.ohoC ActivitvProviderClient.oho© ActivitvProviderRegistrv.ohnC ActivitvProviderService.ohv(c) CallDenormalizerRegistrv nhn(c) CrmownerRecolver nhn@ DatalmnortHandlerinterface nhnC. MeetinaRotService nhrsroomuwner = saata-›gerusersrean = sroomuwner-›gecleanscallerla = soaca-›oeclaclertoonScallerCallSid = $data->qetCallSidO:er->getSoftPhoneInboundDestinationNumberO:572$now = nowO:if (! $this->activityService->teamCanDial($room0wner->getTeam(), $roomOwner->softphone_inboundSreqnon = qetReq1onBvNumberSroomownelthrow new LogicExcention(sprintfl580format: 'Sorry, dialina %s is not available with vour subscriotion.'582Please contact your manager to enable additional destinations.',585$lead = $account = Sopportunity = $contact = $stage = null;tryfScrmService = sthis->crmProviderRegistrv->oetsroomowner->oetTeamo->crm->orovider):ScrmService->setlserSroomOwner):587589591593$crmResolver = app( abstract: CrmOwnerResolver::class, [= Sroomowner->qetTeamo.'providerStua' => Sroombwner->getTeamo->aetcrmconfiaurationO->qetProviderNameO.1):SermService = ScrmPesollver->orenarecrmServi.ce0:ISlead. Saccount. Sonnortunitv. Scontact. Sstadel = ScrmService->matchBvPhone(Sroomdwnen->aetIdo} catch (\Throwable $throwable) {cthie-sloagen-sennon( METHOnI': crm exception', ['exception' => $throwable597599600601602603604605606— 6071:— 609// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happeni 616_611/** @var Models\Activity Sactivity *613Sactivity = SroomOwner-›activities()->create(["'tyDe'=> Models Activitv::TYPE SOFTPHONE INBOUNDprovidenteo cieCTKejEdE File A IDER AW46t6 files →Tx: AutovSo jiminny vCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN' (owner)' ELSE'' END) AS USEr_i041 A1 A40 V65 ^U.emailt.owner_id FROM social_accounts saJOIN users u on v.id = sa.sociable_idJOIN teams t l..n<->l: on t.id = u.team_idWHERE u.team_id = 581 and sa.provider = 'salesforce':SELECT * FROM automated_report_results order by id desc;select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556:select * trom automated reports:where id = 54: # 4fdd41f6-dcf0-30d0-b339-7345381b6044|["pdf" "podcast"]SELECT * FROM automated report results WHERE uuid to bin( '822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid:select * from automated_report_results order by za desc;SELECT * FROMWHEkE 10 = 17191select * fromautomated report results WHERE report id = 54:select * from opportunities where 1d = 75943491SELE * FROM teams WHERE name LIKE "%lesx': # 711, 692. 16067 -Timinnvintearationdlesmills.comselect * from playbooks where team_id = 711; # event 226147SELEd * FROM DLavbook catedonies WHERE Dlavbook 10 = 5515.SELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event':SELECT * SROM eom fields WHERE1d = 2261471SELECT * FROM com field values WHERE com field id = 226147:SELECT * FROM crm_configurations WHERE id = 692SELSCTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '• END) AS user_id,v.emailsa.*t.owner id FROM social accounts saJOIN users u on v.id = sa.sociable idJOIN teams t 1..n<->1: on t.id = u.team idWHERE u.team id = 711 and sa.provider = 'salesforce':SELECT * FROM crm profiles co JOIN users u 1..n<->1: on u.id = co.user id WHERE u.team_id = 711:select * from leads:select * from calendarsSELENT• suppont Dally • In 40m100% 1• Mon 18 May 14:20:38CascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+0 ..• php -l /Users/lukas/jiminny/app/app/Services/Telephony/TextMessagingService.phpzsh:: comnand not tound: ongTnoughtsInoughttor is>I've successfully implemented the fallback token logic for Twilio calls to match the existing dialer pattern. Here's what wasSummary of Changes1. SoftPhoneManager.pnp• Added import: crmuwnerkesolvenOutbound calls ([EMAIL] method)• Replaced direct CRM service user setting with CrmOwnerResolverl•If fallback fails, falls back to original behavior (team owner or user)• Added error logaina for fallback failures• Inbound calls (createInboundActivity method)• Renlaced direct CRM service user setting with CrmlwnerRecolverl•Maintains existing exception handling for CRM failures• Added import: CrmOwnerResolven• buildActivity method•Replaced direct CRM service user setting with CrmOwnerResolver•|f falllback fails and CRM is not required, falls back to team ownen• If CPM is reauired and fallback fails re-throws excention•Replaced direct CRM service user setting with CrmOwnerResolver• |f rallback fails and CRM is not required, falls back to team ownen•If CRM is required and fallback fails, captures exception and returns user's country codeHow It WorksThe imolementation uses the existing CrmOwnerResolver class which:1. First tries the intearation admin's CRM connection2.If that fails with SoctalAccountTokenTnvalidFycention sparches for team members with active CPM connections3. Orders candidates by role (owner, admin, manager, other users)4. Tries each candidate until findina one with a valid connection5. If all fail, throws the original exceptionThis ensures that when the Salesforce admin token has expired. Twilio calls will automaticallv use another active Salesforcetoken from the organization, preventing "Unknown customer" issuesAccent alliAsk anvthing 884-D)« Code SWF-1.6202-28LTF..fo 4 spaces...
|
NULL
|
-4369539491298678499
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormProiectFV faVsco.jsVIewINavigarecodeLarave PhpStormProiectFV faVsco.jsVIewINavigarecodeLaravelKeractor°9 master• laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]« console [PROD] X# console [euyDAvayom BaseServicem BloobirdsD CloseM CloudCalllCloudTalkM ConnectAndSell) M DemoDeck_ Dialpac• C EightByEighturiveNine•J Gmaiu GonoGooclemeerD GoToMeetingGrooveD HubSpotImportJiminnyawlustcalllM MiaratorM NatterboxOficeOrumOutreachlM PinaCentrallM PinaCentralViden1 SalecforceM7 SalecioftTm TeamsToludCActivityController.ong© SoftPhoneManager.php xfinal readonly class SoftPhoneManager implements ConferenceManagerprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\AA console [STAGING]M TwiliorlexM TwilinGlovDirostM TwilinVidenUploaderD Vonage• D Xant0 Zoom→_ZoomBot)ZoomPhoneC) ActivitvCrmFieldsResolver.ohoC) ActivitvLoaService.ohoC ActivitvProviderClient.oho© ActivitvProviderRegistrv.ohnC ActivitvProviderService.ohv(c) CallDenormalizerRegistrv nhn(c) CrmownerRecolver nhn@ DatalmnortHandlerinterface nhnC. MeetinaRotService nhrsroomuwner = saata-›gerusersrean = sroomuwner-›gecleanscallerla = soaca-›oeclaclertoonScallerCallSid = $data->qetCallSidO:er->getSoftPhoneInboundDestinationNumberO:572$now = nowO:if (! $this->activityService->teamCanDial($room0wner->getTeam(), $roomOwner->softphone_inboundSreqnon = qetReq1onBvNumberSroomownelthrow new LogicExcention(sprintfl580format: 'Sorry, dialina %s is not available with vour subscriotion.'582Please contact your manager to enable additional destinations.',585$lead = $account = Sopportunity = $contact = $stage = null;tryfScrmService = sthis->crmProviderRegistrv->oetsroomowner->oetTeamo->crm->orovider):ScrmService->setlserSroomOwner):587589591593$crmResolver = app( abstract: CrmOwnerResolver::class, [= Sroomowner->qetTeamo.'providerStua' => Sroombwner->getTeamo->aetcrmconfiaurationO->qetProviderNameO.1):SermService = ScrmPesollver->orenarecrmServi.ce0:ISlead. Saccount. Sonnortunitv. Scontact. Sstadel = ScrmService->matchBvPhone(Sroomdwnen->aetIdo} catch (\Throwable $throwable) {cthie-sloagen-sennon( METHOnI': crm exception', ['exception' => $throwable597599600601602603604605606— 6071:— 609// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happeni 616_611/** @var Models\Activity Sactivity *613Sactivity = SroomOwner-›activities()->create(["'tyDe'=> Models Activitv::TYPE SOFTPHONE INBOUNDprovidenteo cieCTKejEdE File A IDER AW46t6 files →Tx: AutovSo jiminny vCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN' (owner)' ELSE'' END) AS USEr_i041 A1 A40 V65 ^U.emailt.owner_id FROM social_accounts saJOIN users u on v.id = sa.sociable_idJOIN teams t l..n<->l: on t.id = u.team_idWHERE u.team_id = 581 and sa.provider = 'salesforce':SELECT * FROM automated_report_results order by id desc;select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556:select * trom automated reports:where id = 54: # 4fdd41f6-dcf0-30d0-b339-7345381b6044|["pdf" "podcast"]SELECT * FROM automated report results WHERE uuid to bin( '822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid:select * from automated_report_results order by za desc;SELECT * FROMWHEkE 10 = 17191select * fromautomated report results WHERE report id = 54:select * from opportunities where 1d = 75943491SELE * FROM teams WHERE name LIKE "%lesx': # 711, 692. 16067 -Timinnvintearationdlesmills.comselect * from playbooks where team_id = 711; # event 226147SELEd * FROM DLavbook catedonies WHERE Dlavbook 10 = 5515.SELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event':SELECT * SROM eom fields WHERE1d = 2261471SELECT * FROM com field values WHERE com field id = 226147:SELECT * FROM crm_configurations WHERE id = 692SELSCTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '• END) AS user_id,v.emailsa.*t.owner id FROM social accounts saJOIN users u on v.id = sa.sociable idJOIN teams t 1..n<->1: on t.id = u.team idWHERE u.team id = 711 and sa.provider = 'salesforce':SELECT * FROM crm profiles co JOIN users u 1..n<->1: on u.id = co.user id WHERE u.team_id = 711:select * from leads:select * from calendarsSELENT• suppont Dally • In 40m100% 1• Mon 18 May 14:20:38CascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+0 ..• php -l /Users/lukas/jiminny/app/app/Services/Telephony/TextMessagingService.phpzsh:: comnand not tound: ongTnoughtsInoughttor is>I've successfully implemented the fallback token logic for Twilio calls to match the existing dialer pattern. Here's what wasSummary of Changes1. SoftPhoneManager.pnp• Added import: crmuwnerkesolvenOutbound calls ([EMAIL] method)• Replaced direct CRM service user setting with CrmOwnerResolverl•If fallback fails, falls back to original behavior (team owner or user)• Added error logaina for fallback failures• Inbound calls (createInboundActivity method)• Renlaced direct CRM service user setting with CrmlwnerRecolverl•Maintains existing exception handling for CRM failures• Added import: CrmOwnerResolven• buildActivity method•Replaced direct CRM service user setting with CrmOwnerResolver•|f falllback fails and CRM is not required, falls back to team ownen• If CPM is reauired and fallback fails re-throws excention•Replaced direct CRM service user setting with CrmOwnerResolver• |f rallback fails and CRM is not required, falls back to team ownen•If CRM is required and fallback fails, captures exception and returns user's country codeHow It WorksThe imolementation uses the existing CrmOwnerResolver class which:1. First tries the intearation admin's CRM connection2.If that fails with SoctalAccountTokenTnvalidFycention sparches for team members with active CPM connections3. Orders candidates by role (owner, admin, manager, other users)4. Tries each candidate until findina one with a valid connection5. If all fail, throws the original exceptionThis ensures that when the Salesforce admin token has expired. Twilio calls will automaticallv use another active Salesforcetoken from the organization, preventing "Unknown customer" issuesAccent alliAsk anvthing 884-D)« Code SWF-1.6202-28LTF..fo 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52878
|
1854
|
22
|
2026-05-18T11:20:55.640744+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103255640_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (XIDOCKERDO SlackFileEditViewGoHistoryWindowHelpEU (XIDOCKERDOCKER (docker-compose)81DEV (docker)₴82No Livingconnections1 {"type" : "log""@timestamp":: "2026-05-18T11:20:49Z", "tags" : ["error"ticsearch", "data"], "pid" :7, "message" : "[ConnectionError]:getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}1 {"type": "log","data"],,"@timestamp"2026-05-18T11:20:49Z*tags": ["error""pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}{"type" : "log""@timestamp":"2026-05-18T11:20:49Z", "tags" : ["warning"asticsearch""monitoring"], "pid" :7, "message" : "Unablerevive connection: [URL_WITH_CREDENTIALS] : ["warning", "elasticsearch", "monitoring"],"pid":7, "message": "No living connections"}1 {"type" : "log","@timestamp" : "2026-05-18T11:20:49Z", "tags" : ["warning", "pl"licensing"],"pid":7, "message": "License informationcould not be obtained from Elasticsearch due to Error: No Living connections{"type" : "log", "@timestamp" : "2026-05-18T11:20:49Z","tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:49Z" , "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"1 {"type" : "log""@timestamp": "2026-05-18T11:20:49Z""tags" : ["error", "taskManager", "taskManager"], "pid" :7, "message" : "Failed to pollfor work: Error: NoLiving connections"}docker_lamp_12026-05-18 11:20:46 Running ['artisan' mailbox:batch:process --max-batches=15J4S DONEdocker_lamp_111 '/usr/local/bin/php' 'artisan' mailbox:batch:process --max-batches=15 > '/proc/1/fd/1' 2>&1kibana1 {"type": "log"."@timestamp": "2026-05-18T11:20:51Z", "tags" : ["error","elasticsearch", "data"],"pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana1 {"type" : "log""@timestamp": "2026-05-18T11:20:53Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:53Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"I {"type" : "log", "@timestamp" : "2026-05-18T11:20:53Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:20:54Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktop• View ConfigEnable Watch•HomeDMsActivityFilesLaterMore-Jiminny ...MetromrenCE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka StoyanovaStoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N. Mario Georgiev. Nikolay Ivanov4o James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiE. Lukas Kovalik y... OAppsJira CloudToastSupport Daily • in 40 m100% <78• Mon 18 May 14:20:55Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today ~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] ~Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OG Sign in with GoogleLet's Get Started!не ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
-2582614072602146716
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (XIDOCKERDO SlackFileEditViewGoHistoryWindowHelpEU (XIDOCKERDOCKER (docker-compose)81DEV (docker)₴82No Livingconnections1 {"type" : "log""@timestamp":: "2026-05-18T11:20:49Z", "tags" : ["error"ticsearch", "data"], "pid" :7, "message" : "[ConnectionError]:getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}1 {"type": "log","data"],,"@timestamp"2026-05-18T11:20:49Z*tags": ["error""pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}{"type" : "log""@timestamp":"2026-05-18T11:20:49Z", "tags" : ["warning"asticsearch""monitoring"], "pid" :7, "message" : "Unablerevive connection: [URL_WITH_CREDENTIALS] : ["warning", "elasticsearch", "monitoring"],"pid":7, "message": "No living connections"}1 {"type" : "log","@timestamp" : "2026-05-18T11:20:49Z", "tags" : ["warning", "pl"licensing"],"pid":7, "message": "License informationcould not be obtained from Elasticsearch due to Error: No Living connections{"type" : "log", "@timestamp" : "2026-05-18T11:20:49Z","tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:49Z" , "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"1 {"type" : "log""@timestamp": "2026-05-18T11:20:49Z""tags" : ["error", "taskManager", "taskManager"], "pid" :7, "message" : "Failed to pollfor work: Error: NoLiving connections"}docker_lamp_12026-05-18 11:20:46 Running ['artisan' mailbox:batch:process --max-batches=15J4S DONEdocker_lamp_111 '/usr/local/bin/php' 'artisan' mailbox:batch:process --max-batches=15 > '/proc/1/fd/1' 2>&1kibana1 {"type": "log"."@timestamp": "2026-05-18T11:20:51Z", "tags" : ["error","elasticsearch", "data"],"pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana1 {"type" : "log""@timestamp": "2026-05-18T11:20:53Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:53Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"I {"type" : "log", "@timestamp" : "2026-05-18T11:20:53Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:20:54Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktop• View ConfigEnable Watch•HomeDMsActivityFilesLaterMore-Jiminny ...MetromrenCE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka StoyanovaStoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N. Mario Georgiev. Nikolay Ivanov4o James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiE. Lukas Kovalik y... OAppsJira CloudToastSupport Daily • in 40 m100% <78• Mon 18 May 14:20:55Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today ~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] ~Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OG Sign in with GoogleLet's Get Started!не ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52879
|
1855
|
26
|
2026-05-18T11:20:57.127072+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103257127_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-4235983745889776938
|
-8204421443435123770
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
PhostormINavigarecodeFV faVsco.js°9 master kProledey› D ConferenceHandler• _ [EMAIL]© ConferenceCallbackHandler.phpu conterencemanager.pnpDDIOC7 Event>D ExceptionwJobW ResolveiServiceш VOc)wilioconstants.onoc)TwiioReoositorv.onoUoloaden7 UriGeneratorD UtilityM UuidN WaveformN WehhooksWorkflowM ConfiaurationD ConsoleD Commands>@ ActivitiesD) Analytics)mCnlondarevaum> D HubspotIntegrationapp• Traitsc) AddLavoutEntities.phpc) AutoloaDelavedcommand.pho© BackfillOpportunitvUserFromAccountc 308C3ullhorncommandAostract.onoC)BullhornPinaCommand.onvC) BullhornSearchCommand.ohvC)BullhornSessionCommand.ohd@ CheckActivitvLoagableCommand.ohn 313C) [EMAIL]@ LoaActivitiesCommand.ohnC) ManadeSvncStrateavCommand.nhnlC) Match@nnortunitvActivitiesCommandlC) MiarateProvider nhn.C DurcoDolatod@nnortunitiacCommandlc DocotGovornorl imite nhnle) SondNotLoaged.phpSetupActivityTypeForFollowUp.phpKeractorCActivityController.ongC) SoftPhoneManager.pnp^= laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X# console [euyfinal readonly class SoftPhoneManager implements ConferenceManagerprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Aprivate IW1L1OLL1entbulLaer Stw1L1oLL1entbu1Laer.A console [STAGING]45 Gt ›public function createVo ConferenceManager Activitvcreate Sdata): Models Activitv...;290297private function create0utboundActivitvV0 ConferenceManager SoftPhonelutboundCreate Sdata): Modelso/4private function createInboundActivity(V0\ConferenceManager\SoftPhoneInboundCreate $data): Models\A577$this->logger->debugC__METHOD__, ['callSid' => $data->getCallSid$roomOwner = $data->getUserOSteam = SroomOwner->getleam):$phoneNumber = Sroom0wner->qetSoftPhoneInboundDestinationNumberO:ScallerId = $data->qetCallerIdO:$callerCallSid = Sdata->qetCallSidO:585snow = nowo589if (1 Sthis->activitvService->teamCanDial(Sroom0wner->getTeamO. Sroom0wner->softphone inbound 593Sregion = qetRegionBvNumber(Sroom0wner->softphoneinbound destination. Sroom0wner->getCount 592594sprintfoformat: 'Sorry, dialing %s is not available with your subscription.'Pllease contact vour manaden to enable additional destinations.'es: Sreaion ?? " this numben!.600601$lead = $account = $opportunity = $contact = $stage = null;603+nva605ScrmService = Sthis->crmProviderReqistrv->aet(Sroom0wnen->getTeam@->crm->orovider)ScrmService->setUserSroom0wner):— 607ScrmResolver = app( abstract: CrmOwnerResolver: :class, [— 609611=> Sroomdwner->cetream@->cetcrmconfzourat1ono->cetProvadervameOi613Islead Sacgount, „Sor Accept File &e nt Reiect Fileagga= ScrmService- 3matchByPhone (Tx: AutovSo jiminny vCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN' (owner)' ELSE'' END) AS USEr_i041 A1 A40 V65 ^t.owner_id FROM social_accounts saJOIN users u on v.id = sa.sociable_idJOIN teams t l..n<->l: on t.id = u.team_idWHERE u.team_id = 581 and sa.provider = 'salesforce':SELECT * FROM automated_report_results order by id desc;select x tron reacures,select * from team_features where feature_id = 40;select * from teams where id = 556:select * trom automated reports:where id = 54: # 4fdd41f6-dcf0-30d0-b339-7345381b6044|["pdf" "podcast"]SELECT * FROM automated report results WHERE uuid to bin( '822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;select * from automated_report_results order by za desc;SELECT * FROMWHEKE 10 = 171121select * fromautomated report results WHERE report 1d = 54:select * from opportunities where 1d = 75943491SELE * FROM teamsWHERE name LIKE "%lesh': # 711, 692. 16067-Timinnvintearationdlesmills.comselect * from playbooks where team id = 711: # event 226147SELEd * FROM Dlavbook catedonies WHERE Dlavbook 1d = 55151SELECT * FROM com fields WHERE com confiquration id = 692 and obiect tvne = 'eventi.SELECT * SROM eom fields WHERE1d = 2261471SELECT * FROM com field values WHERE com field id = 226147:SELECT * FROM crm_configurations WHERE id = 692SELSCTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '• END) AS user_id,emailsa.*t.owner id FROM social accounts saJOIN users u on v.id = sa.sociable idJOIN teams t 1..n<->1: on t.id = u.team idWHERE u.team id = 711 and sa.provider = 'salesforce':SELECT * FROM crm profiles co JOIN users u 1..n<->1: on u.id = co.user id WHERE u.team_id = 711:select * from leads:select * from calendarsSELENT: Support Daily - in 40 m100% L2• Mon 18 May 14:20:56AskJiminnyReportActivityServiceTest vCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+0 ..• php -l /Users/lukas/jiminny/app/app/Services/Telephony/TextMessagingService.phpzsh:: comnand not tound: ongTnoughtsInoughttor is>I've successfully implemented the fallback token logic for Twilio calls to match the existing dialer pattern. Here's what wasSummary of Changes1. SoftPhoneManager.pnp• Added import: crmuwnerkesolvenOutbound calls ([EMAIL] method)• Replaced direct CRM service user setting with CrmOwnerResolverl•If fallback fails, falls back to original behavior (team owner or user)• Added error logaina for fallback failures• Inbound calls (createInboundActivity method)• Renlaced direct CRM service user setting with CrmlwnerRecolverl•Maintains existing exception handling for CRM failures• Added import: CrmOwnerResolven• buildActivity method•Replaced direct CRM service user setting with CrmOwnerResolver•|f falllback fails and CRM is not required, falls back to team ownen• If CPM is reauired and fallback fails re-throws excention•Replaced direct CRM service user setting with CrmOwnerResolver• |f rallback fails and CRM is not required, falls back to team ownen•If CRM is required and fallback fails, captures exception and returns user's country codeHow It WorksThe imolementation uses the existing CrmOwnerResolver class which:1. First tries the intearation admin's CRM connection2.If that fails with SoctalAccountTokenTnvalidFycention sparches for team members with active CPM connections3. Orders candidates by role (owner, admin, manager, other users)4. Tries each candidate until findina one with a valid connection5. If all fail, throws the original exceptionThis ensures that when the Salesforce admin token has expired. Twilio calls will automaticallv use another active Salesforcetoken from the organization, preventing "Unknown customer" issuesAccent alliAsk anvthing 884-D)« Code SWF-1.6W Windsurf Teams208-10UTC.8io 4 spaces...
|
52877
|
NULL
|
NULL
|
NULL
|
|
52880
|
1854
|
23
|
2026-05-18T11:21:00.788588+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103260788_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82DOCKER (docker-compose)'/proc/1/fd/1' 2>&11 {"type" : "log""@timestamp": "2026-05-18T11:20:51Z","tags" : ["error"ticsearch", "data"],"pid" :7, "message" : "[ConnectionError]:getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}kibana1 {"type": "log""@timestamp": "2026-05-18T11:20:53Z''tags" : ["warning"elasticsearch", "data"], "pid" :7,"message" : "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:53Z", "tags" : ["warning", "elasticsearch", "data"],"pid" :7,"message": "No livingconnections"}kibanains"1 {"type": "log""@timestamp":"2026-05-18T11:20:53Z", "tags" : ["error", "plug"taskManager""taskManager"],"pid" :7,"message":"Failed to pollfor work: Error: NoLiving connections"}kibana{"type" : "log""@timestamp" : "2026-05-18T11:20:54Z","tags" : ["error", "elasticsearch",, "data"],"pid":7, "message" :"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch: 9200"}docker_lamp_112026-05-18 11:20:50 Running ['artisan'conference:monitor:count] ...5S DONEdocker_lamp_1 | l '/usr/local/bin/php' 'artisan' conference:monitor: count › */proc/1/fd/1' 2>&1kibana1 {"type": "log", "@timestamp" : "2026-05-18T11:20:55Z", "tags" : ["warning"asticsearch", "data"],"pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "tags" : ["warning", "el"message" : "No living connections"}kibanains"1 {"type": "log"!"@timestamp":"2026-05-18T11:20:55Z", "tags" : ["error", "plug, "taskManager","taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log""@timestamp": "2026-05-18T11:20:56Z","tags" : ["error", "elasticsearch",, "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana1 {"type" : "log""@timestamp": "2026-05-18T11:20:58Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:58Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"I {"type" : "log", "@timestamp" : "2026-05-18T11:20:59Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:20:59Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktopo View ConfigEnable WatchHomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N. Mario Georgiev. Nikolay Ivanov4o James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 40 m100% <78• Mon 18 May 14:21:00Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] ~Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OG Sign in with GoogleLet's Get Started!не ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
-6222040974621770300
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82DOCKER (docker-compose)'/proc/1/fd/1' 2>&11 {"type" : "log""@timestamp": "2026-05-18T11:20:51Z","tags" : ["error"ticsearch", "data"],"pid" :7, "message" : "[ConnectionError]:getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}kibana1 {"type": "log""@timestamp": "2026-05-18T11:20:53Z''tags" : ["warning"elasticsearch", "data"], "pid" :7,"message" : "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:20:53Z", "tags" : ["warning", "elasticsearch", "data"],"pid" :7,"message": "No livingconnections"}kibanains"1 {"type": "log""@timestamp":"2026-05-18T11:20:53Z", "tags" : ["error", "plug"taskManager""taskManager"],"pid" :7,"message":"Failed to pollfor work: Error: NoLiving connections"}kibana{"type" : "log""@timestamp" : "2026-05-18T11:20:54Z","tags" : ["error", "elasticsearch",, "data"],"pid":7, "message" :"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch: 9200"}docker_lamp_112026-05-18 11:20:50 Running ['artisan'conference:monitor:count] ...5S DONEdocker_lamp_1 | l '/usr/local/bin/php' 'artisan' conference:monitor: count › */proc/1/fd/1' 2>&1kibana1 {"type": "log", "@timestamp" : "2026-05-18T11:20:55Z", "tags" : ["warning"asticsearch", "data"],"pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "tags" : ["warning", "el"message" : "No living connections"}kibanains"1 {"type": "log"!"@timestamp":"2026-05-18T11:20:55Z", "tags" : ["error", "plug, "taskManager","taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log""@timestamp": "2026-05-18T11:20:56Z","tags" : ["error", "elasticsearch",, "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana1 {"type" : "log""@timestamp": "2026-05-18T11:20:58Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:20:58Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"I {"type" : "log", "@timestamp" : "2026-05-18T11:20:59Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:20:59Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktopo View ConfigEnable WatchHomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N. Mario Georgiev. Nikolay Ivanov4o James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 40 m100% <78• Mon 18 May 14:21:00Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] ~Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OG Sign in with GoogleLet's Get Started!не ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
52878
|
NULL
|
NULL
|
NULL
|
|
52881
|
1855
|
27
|
2026-05-18T11:21:00.793952+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103260793_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhostormProiect vVIewINavigarecodeLaravelKeractorJ PhostormProiect vVIewINavigarecodeLaravelKeractorJOOISWindowFV faVsco.js°9 master kCActivityController.ong=custom.log= laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]« console [PROD] X# console [euy› D ConferenceHandlerv D [EMAIL] conterencecallbackhlanaler.onpConferenceManager.phpDDIOC Event>D Exceptione Job>W ResolvelService,DVOc)wilioconstants.onoc)TwiioReoositorv.onoUoloaden7 UriGeneratorD UtilityM UuidIM Waveformn WehhooksWorkflow> M ConfiaurationD ConsoleM Commande>@ Activities>@ Analytics)mCnlondarev0 erm> D Hubspot› IntegrationApp> D Traitsc) AddLavoutEntities.phpfinal readonly class SoftPhoneManager implements ConferenceManagerprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\AA console [STAGING]286291c) AutoloaDelavedcommand.phoc) BacktillOpportunityUserFromaccountC3ullhorncommandAostract.onoC) BullhornPinaCommand.ohvC) BullhornSearchCommand.onvC)BullhornSessionCommand.ohd@ CheckActivitvLoagableCommand.ohp© CleanDuplicateFieldDataCommand.oh325C) [EMAIL]@ LoaActivitiesCommand.ohnC) ManadeSvncStrateavCommand.nhnlC) MatchCrmOhiectsCommand.nhnC) Match@nnortunitvActivitiesCommandl(C) MiarateProvider nhnlC) ProceccHuhsnot@biectsSvncRatches328329331(c DurcoDolatod@nnortunitiacCommandlc DocotGovornorl imite nhnl(@) SendNotLoaged.phpSetupActivityTypeForFollowUp.php335$roomOwner = $data->getUserOsrean = sroomuwner-›geclean$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();scallerid = soaca-›gectallerto$callerCallSid = $data->getCallSidO:572574576if (! $this-›activityService->teamCanDial($room0wner->getTeam(), $room0wner->softphone_inbound.Sregnon = getReq1onBvNumberSroom0wner->softphone1nbound destination. sroomowner->getcountthrow new Looncexcentiontsprintfl582'Sorry, dialina %s is not available with vour subscrintion.'Please contact your manager to enable additional destinations.',es: Sregion 2? "this numben!584585587589$lead = $account = Sopportunity = $contact = $stage = null;tryfSermService = sthis->crmProviderReqistrv->aet(Sroomowner->qetTeamo->crm->orovider):SermService->setlserSroomQwner)594$crmResolver = app( abstract: CrmOwnerResolver::class, [team' => Sroomuwner->oet eamor'providerStua' => Sroombwner->getTeamo->aetcrmconfiaurationO->aetProviderNameOScrmService = ScrmResolver->orepareCrmService0:Slead. Saccount. Sonnortunitv. Scontact. Sstadel = ScrmService->matchBvPhoneScallerTd.Sroomdwnen->aetTd} catch (\Throwable $throwable) {Cthic-sloadon-sonnon METHOnI': crm exception', ['exception' => $throwable,l597599600601602603604605606— 607608—609// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happeni 611/** @var Models\Activity Sactivity *Sactivity = Sroom0wner->activities->create(["type T 3 of3 editsAccept File &+ ctxi RéfeytFileYPE«SOFKPHOME2INBOUND"provzder'=> Models Activitv::PROVIDER_ TwILTO..hac heon rectored /l Pollback II Confiaure (a minute aao)Tx: AutovSo jiminny vCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN' (owner)' ELSE' END) AS USer_1041 A1 A40 V65 ^U.emailt.owner_id FROM social_accounts saJOIN users u on v.id = sa.sociable_idJOIN teams t l..n<->l: on t.id = u.team_idWHERE u.team_id = 581 and sa.provider = 'salesforce':SELECT * FROM automated_report_results order by id desc;select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556:select * trom automated reports:where id = 54: # 4fdd41f6-dcf0-30d0-b339-7345381b6044|["pdf" "podcast"]SELECT * FROM automated report results WHERE uuid to bin( '822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;select * from automated_report_results order by za desc;SELECT * FROMWHEkE 10 = 17191select * fromautomated report results WHERE report id = 54:select * from opportunities where 1d = 75943491SELE * FROM teams WHERE name LIKE "%lesx': # 711, 692. 16067 -Timinnvintearationdlesmills.comselect * from playbooks where team_id = 711; # event 226147SELEd * FROM DLavbook catedonies WHERE Dlavbook 10 = 55151SELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event':SELECT * SROM eom fields WHERE1d = 2261471SELECT * FROM com field values WHERE com field id = 226147:SELECT * FROM crm_configurations WHERE id = 692SELSCTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '• END) AS user_id,emailsa.*t.owner id FROM social accounts saJOIN users u on v.id = sa.sociable idJOIN teams t 1..n<->1: on t.id = u.team idWHERE u.team id = 711 and sa.provider = 'salesforce':SELECT * FROM crm profiles co JOIN users u 1..n<->1: on u.id = co.user id WHERE u.team_id = 711:select * from leads:select * from calendarsSELENT: Support Daily - in 40 m100% S2• Mon 18 May 14:21:00AskJiminnyReportActivityServiceTest vCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+0 ..• php -l /Users/lukas/jiminny/app/app/Services/Telephony/TextMessagingService.phpzsh:: comnand not tound: ongTnoughtsInoughttor is>I've successfully implemented the fallback token logic for Twilio calls to match the existing dialer pattern. Here's what wasSummary of Changes1. SoftPhoneManager.php• Added import: crmuwnerkesolvenOutbound calls ([EMAIL] method)• Replaced direct CRM service user setting with CrmOwnerResolverl•If fallback fails, falls back to original behavior (team owner or user)• Added error logaina for fallback failures• Inbound calls (createInboundActivity method)• Renlaced direct CRM service user setting with CrmlwnerRecolverl•Maintains existing exception handling for CRM failures• Added import: CrmOwnerResolven• buildActivity method•Replaced direct CRM service user setting with CrmOwnerResolver•|f falllback fails and CRM is not required, falls back to team ownen• If CPM is reauired and fallback fails re-throws excention•Replaced direct CRM service user setting with CrmOwnerResolver• |f rallback fails and CRM is not required, falls back to team ownen•If CRM is required and fallback fails, captures exception and returns user's country codeHow It WorksThe imolementation uses the existing CrmOwnerResolver class which:1. First tries the intearation admin's CRM connection2.If that fails with SoctalAccountTokenTnvalidFycention sparches for team members with active CPM connections3. Orders candidates by role (owner, admin, manager, other users)4. Tries each candidate until findina one with a valid connection5. If all fail, throws the original exceptionThis ensures that when the Salesforce admin token has expired. Twilio calls will automaticallv use another active Salesforcetoken from the organization, preventing "Unknown customer" issuesAccent alliAsk anvthina (884-L)« Code SWF-1.6WN Windsurf Teams220-12 UTC.8io 4 spaces...
|
NULL
|
-1468332536874354962
|
NULL
|
click
|
ocr
|
NULL
|
PhostormProiect vVIewINavigarecodeLaravelKeractorJ PhostormProiect vVIewINavigarecodeLaravelKeractorJOOISWindowFV faVsco.js°9 master kCActivityController.ong=custom.log= laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]« console [PROD] X# console [euy› D ConferenceHandlerv D [EMAIL] conterencecallbackhlanaler.onpConferenceManager.phpDDIOC Event>D Exceptione Job>W ResolvelService,DVOc)wilioconstants.onoc)TwiioReoositorv.onoUoloaden7 UriGeneratorD UtilityM UuidIM Waveformn WehhooksWorkflow> M ConfiaurationD ConsoleM Commande>@ Activities>@ Analytics)mCnlondarev0 erm> D Hubspot› IntegrationApp> D Traitsc) AddLavoutEntities.phpfinal readonly class SoftPhoneManager implements ConferenceManagerprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\AA console [STAGING]286291c) AutoloaDelavedcommand.phoc) BacktillOpportunityUserFromaccountC3ullhorncommandAostract.onoC) BullhornPinaCommand.ohvC) BullhornSearchCommand.onvC)BullhornSessionCommand.ohd@ CheckActivitvLoagableCommand.ohp© CleanDuplicateFieldDataCommand.oh325C) [EMAIL]@ LoaActivitiesCommand.ohnC) ManadeSvncStrateavCommand.nhnlC) MatchCrmOhiectsCommand.nhnC) Match@nnortunitvActivitiesCommandl(C) MiarateProvider nhnlC) ProceccHuhsnot@biectsSvncRatches328329331(c DurcoDolatod@nnortunitiacCommandlc DocotGovornorl imite nhnl(@) SendNotLoaged.phpSetupActivityTypeForFollowUp.php335$roomOwner = $data->getUserOsrean = sroomuwner-›geclean$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();scallerid = soaca-›gectallerto$callerCallSid = $data->getCallSidO:572574576if (! $this-›activityService->teamCanDial($room0wner->getTeam(), $room0wner->softphone_inbound.Sregnon = getReq1onBvNumberSroom0wner->softphone1nbound destination. sroomowner->getcountthrow new Looncexcentiontsprintfl582'Sorry, dialina %s is not available with vour subscrintion.'Please contact your manager to enable additional destinations.',es: Sregion 2? "this numben!584585587589$lead = $account = Sopportunity = $contact = $stage = null;tryfSermService = sthis->crmProviderReqistrv->aet(Sroomowner->qetTeamo->crm->orovider):SermService->setlserSroomQwner)594$crmResolver = app( abstract: CrmOwnerResolver::class, [team' => Sroomuwner->oet eamor'providerStua' => Sroombwner->getTeamo->aetcrmconfiaurationO->aetProviderNameOScrmService = ScrmResolver->orepareCrmService0:Slead. Saccount. Sonnortunitv. Scontact. Sstadel = ScrmService->matchBvPhoneScallerTd.Sroomdwnen->aetTd} catch (\Throwable $throwable) {Cthic-sloadon-sonnon METHOnI': crm exception', ['exception' => $throwable,l597599600601602603604605606— 607608—609// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happeni 611/** @var Models\Activity Sactivity *Sactivity = Sroom0wner->activities->create(["type T 3 of3 editsAccept File &+ ctxi RéfeytFileYPE«SOFKPHOME2INBOUND"provzder'=> Models Activitv::PROVIDER_ TwILTO..hac heon rectored /l Pollback II Confiaure (a minute aao)Tx: AutovSo jiminny vCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN' (owner)' ELSE' END) AS USer_1041 A1 A40 V65 ^U.emailt.owner_id FROM social_accounts saJOIN users u on v.id = sa.sociable_idJOIN teams t l..n<->l: on t.id = u.team_idWHERE u.team_id = 581 and sa.provider = 'salesforce':SELECT * FROM automated_report_results order by id desc;select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556:select * trom automated reports:where id = 54: # 4fdd41f6-dcf0-30d0-b339-7345381b6044|["pdf" "podcast"]SELECT * FROM automated report results WHERE uuid to bin( '822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;select * from automated_report_results order by za desc;SELECT * FROMWHEkE 10 = 17191select * fromautomated report results WHERE report id = 54:select * from opportunities where 1d = 75943491SELE * FROM teams WHERE name LIKE "%lesx': # 711, 692. 16067 -Timinnvintearationdlesmills.comselect * from playbooks where team_id = 711; # event 226147SELEd * FROM DLavbook catedonies WHERE Dlavbook 10 = 55151SELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event':SELECT * SROM eom fields WHERE1d = 2261471SELECT * FROM com field values WHERE com field id = 226147:SELECT * FROM crm_configurations WHERE id = 692SELSCTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '• END) AS user_id,emailsa.*t.owner id FROM social accounts saJOIN users u on v.id = sa.sociable idJOIN teams t 1..n<->1: on t.id = u.team idWHERE u.team id = 711 and sa.provider = 'salesforce':SELECT * FROM crm profiles co JOIN users u 1..n<->1: on u.id = co.user id WHERE u.team_id = 711:select * from leads:select * from calendarsSELENT: Support Daily - in 40 m100% S2• Mon 18 May 14:21:00AskJiminnyReportActivityServiceTest vCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+0 ..• php -l /Users/lukas/jiminny/app/app/Services/Telephony/TextMessagingService.phpzsh:: comnand not tound: ongTnoughtsInoughttor is>I've successfully implemented the fallback token logic for Twilio calls to match the existing dialer pattern. Here's what wasSummary of Changes1. SoftPhoneManager.php• Added import: crmuwnerkesolvenOutbound calls ([EMAIL] method)• Replaced direct CRM service user setting with CrmOwnerResolverl•If fallback fails, falls back to original behavior (team owner or user)• Added error logaina for fallback failures• Inbound calls (createInboundActivity method)• Renlaced direct CRM service user setting with CrmlwnerRecolverl•Maintains existing exception handling for CRM failures• Added import: CrmOwnerResolven• buildActivity method•Replaced direct CRM service user setting with CrmOwnerResolver•|f falllback fails and CRM is not required, falls back to team ownen• If CPM is reauired and fallback fails re-throws excention•Replaced direct CRM service user setting with CrmOwnerResolver• |f rallback fails and CRM is not required, falls back to team ownen•If CRM is required and fallback fails, captures exception and returns user's country codeHow It WorksThe imolementation uses the existing CrmOwnerResolver class which:1. First tries the intearation admin's CRM connection2.If that fails with SoctalAccountTokenTnvalidFycention sparches for team members with active CPM connections3. Orders candidates by role (owner, admin, manager, other users)4. Tries each candidate until findina one with a valid connection5. If all fail, throws the original exceptionThis ensures that when the Salesforce admin token has expired. Twilio calls will automaticallv use another active Salesforcetoken from the organization, preventing "Unknown customer" issuesAccent alliAsk anvthina (884-L)« Code SWF-1.6WN Windsurf Teams220-12 UTC.8io 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52882
|
1854
|
24
|
2026-05-18T11:21:03.866995+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103263866_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.016666668,"height":0.02111111},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.02111111},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.025555555},"on_screen":false,"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.0,"top":0.0,"width":0.014583333,"height":0.025555555},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7953126764475839635
|
8095951852832531081
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52883
|
1855
|
28
|
2026-05-18T11:21:03.889169+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103263889_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.007978723,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"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.27027926,"top":1.0,"width":0.006981383,"height":0.0},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3143271682935527877
|
8095951852832531081
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…...
|
52881
|
NULL
|
NULL
|
NULL
|
|
52887
|
1854
|
26
|
2026-05-18T11:21:19.316035+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103279316_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82DOCKER (docker-compose)ticsearch"{"type": "log""@timestamp" : "2026-05-18T11:21:11Z","tags" : ["error""pid":7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}docker_1amp_12026-05-18 11:21:10 Running ['artisan'conference:monitor:start]docker_lamp_11 '/usr/local/bin/php' 'artisan'conference:monitor:start1 {"type": "log""@timestamp": "2026-05-18T11:21:13Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:21:13Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibana1 {"type" : "log", "@timestamp" : "2026-05-18T11:21:13Z", "tags" : ["error", "plugins""taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type" : "log", "@timestamp" : "2026-05-18T11:21:14Z" , "tags" : ["error","elasticsearch",, "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}docker_lamp_1 |2026-05-18 11:21:13 Running ['artisan' conference:monitor:end]3S DONEdocker_lamp_11 l '/usr/local/bin/php' 'artisan' conference:monitor:end › */proc/1/fd1 {"type":"log", "@timestamp" : "2026-05-18T11:21:16Z", "tags" : ["error"ticsearch",, "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type" : "log","@timestamp":"2026-05-18T11:21:16Z" , "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:21:16Z" , "tags" : ["warning", "elasticsearch", "data"],"pid":7, "message": "No living connections"}1 {"type": "log","@timestamp":"2026-05-18T11:21:17Z""tags" : ["error", "plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: Noconnections"}1 {"type" : "log""@timestamp":"2026-05-18T11:21:19Z","tags" : ["warning"asticsearch", "data"], "pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:19Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No livingconnections"}1 {"type": "log", "@timestamp": "2026-05-18T11:21:19Z", "tags" : ["warning", "pl,"licensing"],"pid" :7,"message": "License information could not be obtained from Elasticsearch due to Error: No Living connectionserror"}View in Docker Desktopo View ConfigEnable Watch•HomeDMsActivityFilesLaterMore-Jiminny ...MetromrenCE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N8. Mario GeorgievNikolay Ivanov4o James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiE. Lukas Kovalik y... OAppsJira CloudToastSupport Daily • in 39 m100% <78• Mon 18 May 14:21:19Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] •Update your information::LANGUAGES SPOKEN DURING CALLSEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started!G Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
-8754888289762373754
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82DOCKER (docker-compose)ticsearch"{"type": "log""@timestamp" : "2026-05-18T11:21:11Z","tags" : ["error""pid":7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}docker_1amp_12026-05-18 11:21:10 Running ['artisan'conference:monitor:start]docker_lamp_11 '/usr/local/bin/php' 'artisan'conference:monitor:start1 {"type": "log""@timestamp": "2026-05-18T11:21:13Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:21:13Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibana1 {"type" : "log", "@timestamp" : "2026-05-18T11:21:13Z", "tags" : ["error", "plugins""taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type" : "log", "@timestamp" : "2026-05-18T11:21:14Z" , "tags" : ["error","elasticsearch",, "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}docker_lamp_1 |2026-05-18 11:21:13 Running ['artisan' conference:monitor:end]3S DONEdocker_lamp_11 l '/usr/local/bin/php' 'artisan' conference:monitor:end › */proc/1/fd1 {"type":"log", "@timestamp" : "2026-05-18T11:21:16Z", "tags" : ["error"ticsearch",, "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type" : "log","@timestamp":"2026-05-18T11:21:16Z" , "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:21:16Z" , "tags" : ["warning", "elasticsearch", "data"],"pid":7, "message": "No living connections"}1 {"type": "log","@timestamp":"2026-05-18T11:21:17Z""tags" : ["error", "plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: Noconnections"}1 {"type" : "log""@timestamp":"2026-05-18T11:21:19Z","tags" : ["warning"asticsearch", "data"], "pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:19Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No livingconnections"}1 {"type": "log", "@timestamp": "2026-05-18T11:21:19Z", "tags" : ["warning", "pl,"licensing"],"pid" :7,"message": "License information could not be obtained from Elasticsearch due to Error: No Living connectionserror"}View in Docker Desktopo View ConfigEnable Watch•HomeDMsActivityFilesLaterMore-Jiminny ...MetromrenCE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "N8. Mario GeorgievNikolay Ivanov4o James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiE. Lukas Kovalik y... OAppsJira CloudToastSupport Daily • in 39 m100% <78• Mon 18 May 14:21:19Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] •Update your information::LANGUAGES SPOKEN DURING CALLSEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started!G Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52890
|
1854
|
28
|
2026-05-18T11:21:51.427308+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103311427_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82"@timestamp": "2026-05-18T11:21:46Z"ticsearch""tags" : ["error""message":"[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}1 {"type" : "log""@timestamp" : "2026-05-18T11:21:47Z", "tags" : ["warning".asticsearch", "data"],"pid" :7,'"message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:47Z", "tags" : ["warning"asticsearch", "data"],"pid" :7,connections"}1 {"type" : "log","@timestamp""2026-05-18T11:21:47Z""tags" : ["error", "taskManager"Living connections"}"taskManager"], "pid":7,"message":"Failed to poll for work: Error: No1 {"type" : "log","@timestamp" : "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7,"message" : "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,:"No livingconnections"}1 {"type":"loq""@timestamp": "2026-05-18T11:21:49Z","tags" : ["warning","licensing"], "pid" :7,"message": "License information could not be obtained from ELasticsearch due to Error: No Living connections error"}1 {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z" , "tags" : ["error"ticsearch""data"], "pid" :7,"message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}I {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z", "tags" : ["error"ticsearch",, "data"], "pid":7, "message" :"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}I {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "monitoring"],"pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "monitoring"],"pid" :7, "message" : "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z""tags" : ["warning", "plugins", "licensing"], "pid":7, "message" : "License information could not be obtained from Elasticsearch due to Error: No Living connections error"}1 {"type" : "log","@timestamp" : "2026-05-18T11:21:49Z""tags": ["warning"asticsearch", "data"], "pid" :7,"message": "Unable to revive connection: [URL_WITH_CREDENTIALS] :"2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "data"], "pid":7, "message": "No living connections"}1 {"type": "log", "@timestamp": "2026-05-18T11:21:50Z","tags" : ["error", "plug, "taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}View in Docker Desktop• View ConfigHomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "Ndi. Mario Georgiev. Nikolay Ivanov4o James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 39 m100% <78• Mon 18 May 14:21:50Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] •Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started!G Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
1325564550680394291
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82"@timestamp": "2026-05-18T11:21:46Z"ticsearch""tags" : ["error""message":"[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}1 {"type" : "log""@timestamp" : "2026-05-18T11:21:47Z", "tags" : ["warning".asticsearch", "data"],"pid" :7,'"message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:47Z", "tags" : ["warning"asticsearch", "data"],"pid" :7,connections"}1 {"type" : "log","@timestamp""2026-05-18T11:21:47Z""tags" : ["error", "taskManager"Living connections"}"taskManager"], "pid":7,"message":"Failed to poll for work: Error: No1 {"type" : "log","@timestamp" : "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7,"message" : "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,:"No livingconnections"}1 {"type":"loq""@timestamp": "2026-05-18T11:21:49Z","tags" : ["warning","licensing"], "pid" :7,"message": "License information could not be obtained from ELasticsearch due to Error: No Living connections error"}1 {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z" , "tags" : ["error"ticsearch""data"], "pid" :7,"message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}I {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z", "tags" : ["error"ticsearch",, "data"], "pid":7, "message" :"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}I {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "monitoring"],"pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "monitoring"],"pid" :7, "message" : "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:21:49Z""tags" : ["warning", "plugins", "licensing"], "pid":7, "message" : "License information could not be obtained from Elasticsearch due to Error: No Living connections error"}1 {"type" : "log","@timestamp" : "2026-05-18T11:21:49Z""tags": ["warning"asticsearch", "data"], "pid" :7,"message": "Unable to revive connection: [URL_WITH_CREDENTIALS] :"2026-05-18T11:21:49Z", "tags" : ["warning", "elasticsearch", "data"], "pid":7, "message": "No living connections"}1 {"type": "log", "@timestamp": "2026-05-18T11:21:50Z","tags" : ["error", "plug, "taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}View in Docker Desktop• View ConfigHomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya Dimitrova ELe Todor Stamatov "Ndi. Mario Georgiev. Nikolay Ivanov4o James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 39 m100% <78• Mon 18 May 14:21:50Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] •Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started!G Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52892
|
1855
|
33
|
2026-05-18T11:21:54.084707+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103314084_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
41
1
40
65
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993
SELECT * FROM users WHERE id = 25061;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 994;
SELECT * FROM crm_profiles WHERE user_id = 25061;
select * from crm_configurations where id = 834;
SELECT * FROM teams WHERE id = 882;
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 = 882 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;
SELECT * FROM contacts where crm_configuration_id = 834;
SELECT * FROM opportunities WHERE team_id = 933
# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');
AND id IN (8482561,18352941,19042734,19232139,19445140,19472541);
SELECT * FROM opportunity_contacts
WHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 485; #
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
select crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id
where crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')
# and l.converted_at IS NOT NULL
;
# [PASSWORD_DOTS]
SELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')
and opportunity_id IS NULL
order by id desc;
SELECT * FROM teams WHERE id = 604; # 598
SELECT * FROM activities WHERE id = 74410828; # [EMAIL]
SELECT * FROM accounts WHERE id = 20068382;
SELECT * FROM accounts WHERE id = 35186038;
SELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;
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 = 559 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;
select * from sidekick_settings where team_id = 781;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100
SELECT * FROM crm_layouts WHERE crm_configuration_id = 711;
SELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL
and is_internal = 0 and status = 'completed'
order by id desc;
SELECT * FROM crm_layout_entities
WHERE crm_layout_id IN (2352, 2353);
;
SELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;
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 = 556 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;
SELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;
select * from contacts
where crm_configuration_id = 530
and crm_provider_id = 872252;
select * from activities where crm_configuration_id = 530
and user_id = 14343 and type like '%softphone%'
and created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);
SELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t
JOIN crm_configurations c ON t.id = c.team_id
WHERE t.status = 'active';
SELECT * FROM teams where id = 1091;
SELECT * FROM crm_configurations where team_id = 1091;
SELECT * FROM activity_providers where team_id = 1091;
SELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT * FROM teams WHERE name LIKE '%Leadventure%';
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 = 1091 and sa.provider = 'salesforce';
SELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812
SELECT * FROM teams where id = 862;
SELECT * FROM crm_configurations where team_id = 862;
SELECT * FROM activity_providers where team_id = 862;
SELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT t.id, crm.id, crm.provider, ap.* FROM teams t
join crm_configurations crm on t.id = crm.team_id
join activity_providers ap on t.id = ap.team_id
where t.status = 'active' and ap.is_enabled = 1
and crm.provider = 'hubspot'
and ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',
'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');
SELECT * FROM teams where id = 1068;
SELECT * FROM crm_configurations where team_id = 1068;
SELECT * FROM activity_providers where team_id = 1068;
SELECT * FROM activities a
where crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')
and a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'
)
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by a.id desc;
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 = 1068 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262
SELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;
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 = 882 and sa.provider = 'hubspot';
select * from crm_layouts where crm_configuration_id = 834;
select * from crm_layout_entities where crm_layout_id = 2780;
select * from crm_fields where id IN (321153,321192,321193,321194);
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
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 = 1057 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
SELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8
SELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20
SELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10
SELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2
# [PASSWORD_DOTS]
SELECT * FR...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.007978723,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"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.27027926,"top":1.0,"width":0.006981383,"height":0.0},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\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.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.47573137,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.4867021,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.51329786,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5242686,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.70611703,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"41","depth":4,"bounds":{"left":0.6761968,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.6878325,"top":0.123703115,"width":0.00731383,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"40","depth":4,"bounds":{"left":0.69714093,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"65","depth":4,"bounds":{"left":0.7094415,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.72140956,"top":0.12210695,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.7287234,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-01-01';\nand id IN (32415, 32416);\n# and id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;\n\nSELECT * FROM activities WHERE uuid_to_bin('67cebfc2-ed56-44a2-8c68-7a0286ed8618') = uuid; # 79763436\n\nSELECT email_provider_id, COUNT(*) as count, GROUP_CONCAT(id) as ids, GROUP_CONCAT(status) as statuses\nFROM text_relays\nWHERE email_provider_id IN ('19e2027868a64b42', '19e2033ed8ea6b10')\nGROUP BY email_provider_id;\nSELECT id, status, telephony_provider_id, created_at\nFROM activities\nWHERE id IN (80028719, 80028846);\nSELECT id, status, code, email_sent_at, created_at, updated_at\nFROM text_relays\nWHERE id IN (32415, 32416);\nSELECT id, status, code, sender, recipient, created_at\nFROM text_relays\nWHERE sender LIKE '%mario.georgiev%' OR sender LIKE '%stoyan.tomov%'\nORDER BY created_at DESC\nLIMIT 10;\n\nSELECT id, uuid, status, code, sender, recipient, created_at, updated_at\nFROM text_relays\nWHERE uuid = uuid_to_bin('0626141c-27a6-4d8c-aff8-7c8020a2c656');\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nselect * from teams where id = 1;\n\nselect * from roles;","depth":4,"on_screen":true,"value":"SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-01-01';\nand id IN (32415, 32416);\n# and id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;\n\nSELECT * FROM activities WHERE uuid_to_bin('67cebfc2-ed56-44a2-8c68-7a0286ed8618') = uuid; # 79763436\n\nSELECT email_provider_id, COUNT(*) as count, GROUP_CONCAT(id) as ids, GROUP_CONCAT(status) as statuses\nFROM text_relays\nWHERE email_provider_id IN ('19e2027868a64b42', '19e2033ed8ea6b10')\nGROUP BY email_provider_id;\nSELECT id, status, telephony_provider_id, created_at\nFROM activities\nWHERE id IN (80028719, 80028846);\nSELECT id, status, code, email_sent_at, created_at, updated_at\nFROM text_relays\nWHERE id IN (32415, 32416);\nSELECT id, status, code, sender, recipient, created_at\nFROM text_relays\nWHERE sender LIKE '%mario.georgiev%' OR sender LIKE '%stoyan.tomov%'\nORDER BY created_at DESC\nLIMIT 10;\n\nSELECT id, uuid, status, code, sender, recipient, created_at, updated_at\nFROM text_relays\nWHERE uuid = uuid_to_bin('0626141c-27a6-4d8c-aff8-7c8020a2c656');\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nselect * from teams where id = 1;\n\nselect * from roles;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-1262495307487737336
|
957587847100412741
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
41
1
40
65
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993
SELECT * FROM users WHERE id = 25061;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 994;
SELECT * FROM crm_profiles WHERE user_id = 25061;
select * from crm_configurations where id = 834;
SELECT * FROM teams WHERE id = 882;
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 = 882 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;
SELECT * FROM contacts where crm_configuration_id = 834;
SELECT * FROM opportunities WHERE team_id = 933
# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');
AND id IN (8482561,18352941,19042734,19232139,19445140,19472541);
SELECT * FROM opportunity_contacts
WHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 485; #
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
select crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id
where crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')
# and l.converted_at IS NOT NULL
;
# [PASSWORD_DOTS]
SELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')
and opportunity_id IS NULL
order by id desc;
SELECT * FROM teams WHERE id = 604; # 598
SELECT * FROM activities WHERE id = 74410828; # [EMAIL]
SELECT * FROM accounts WHERE id = 20068382;
SELECT * FROM accounts WHERE id = 35186038;
SELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;
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 = 559 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;
select * from sidekick_settings where team_id = 781;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100
SELECT * FROM crm_layouts WHERE crm_configuration_id = 711;
SELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL
and is_internal = 0 and status = 'completed'
order by id desc;
SELECT * FROM crm_layout_entities
WHERE crm_layout_id IN (2352, 2353);
;
SELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;
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 = 556 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;
SELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;
select * from contacts
where crm_configuration_id = 530
and crm_provider_id = 872252;
select * from activities where crm_configuration_id = 530
and user_id = 14343 and type like '%softphone%'
and created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);
SELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t
JOIN crm_configurations c ON t.id = c.team_id
WHERE t.status = 'active';
SELECT * FROM teams where id = 1091;
SELECT * FROM crm_configurations where team_id = 1091;
SELECT * FROM activity_providers where team_id = 1091;
SELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT * FROM teams WHERE name LIKE '%Leadventure%';
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 = 1091 and sa.provider = 'salesforce';
SELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812
SELECT * FROM teams where id = 862;
SELECT * FROM crm_configurations where team_id = 862;
SELECT * FROM activity_providers where team_id = 862;
SELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT t.id, crm.id, crm.provider, ap.* FROM teams t
join crm_configurations crm on t.id = crm.team_id
join activity_providers ap on t.id = ap.team_id
where t.status = 'active' and ap.is_enabled = 1
and crm.provider = 'hubspot'
and ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',
'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');
SELECT * FROM teams where id = 1068;
SELECT * FROM crm_configurations where team_id = 1068;
SELECT * FROM activity_providers where team_id = 1068;
SELECT * FROM activities a
where crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')
and a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'
)
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by a.id desc;
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 = 1068 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262
SELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;
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 = 882 and sa.provider = 'hubspot';
select * from crm_layouts where crm_configuration_id = 834;
select * from crm_layout_entities where crm_layout_id = 2780;
select * from crm_fields where id IN (321153,321192,321193,321194);
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
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 = 1057 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
SELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8
SELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20
SELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10
SELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2
# [PASSWORD_DOTS]
SELECT * FR...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52893
|
1854
|
29
|
2026-05-18T11:21:59.728370+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103319728_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)X t1DOCKER (docker-compose){"type": "log""@timestamp": "2026-05-18T11:21:49Z"asticsearch", "data"],:"No livingconnections"},"tags" : ["warning"I {"type" : "log", "@timestamp" : "2026-05-18T11:21:50Z""tags" : ["error", "taskManager""taskManager"], "pid" :7, "message":"Failed to pollfor work: Error: NoLiving connections"}{"type" : "log","@timestamp":"2026-05-18T11:21:51Z", "tags" : ["error""pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}{"type" : "log""@timestamp":"2026-05-18T11:21:53Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:53Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7,"message" : "No living1 {"type" : "log"connections'"}"@timestamp" : "2026-05-18T11:21:53Z", "tags" : ["error"ins",,"plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLivingconnections"}kibanaticsearch"1 {"type": "log", "@timestamp": "2026-05-18T11:21:54Z", "tags" : ["error", "elas"data"], "pid" :7,"message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}1 {"type": "log","@timestamp" : "2026-05-18T11:21:56Z", "tags" : ["warning"asticsearch", "data"],"pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibanains"1 {"type": "log"!"@timestamp": "2026-05-18T11:21:56Z""tags" : ["error", "plug, "taskManager","taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log""@timestamp": "2026-05-18T11:21:56Z", "tags" : ["error", "elasticsearch", "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana1 {"type" : "log""@timestamp": "2026-05-18T11:21:58Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:59Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibana1 {"type" : "log"!ins","@timestamp": "2026-05-18T11:21:59Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:21:59Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktopo View ConfigEnable WatchHomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil VasilevP. Galya Dimitrova ELe Todor Stamatov "Ndi. Mario Georgiev. Nikolay Ivanov4o James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 39 m100% <78• Mon 18 May 14:21:59Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today ~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] ~Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OG Sign in with GoogleLet's Get Started!не ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
NULL
|
4527928327274942145
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)X t1DOCKER (docker-compose){"type": "log""@timestamp": "2026-05-18T11:21:49Z"asticsearch", "data"],:"No livingconnections"},"tags" : ["warning"I {"type" : "log", "@timestamp" : "2026-05-18T11:21:50Z""tags" : ["error", "taskManager""taskManager"], "pid" :7, "message":"Failed to pollfor work: Error: NoLiving connections"}{"type" : "log","@timestamp":"2026-05-18T11:21:51Z", "tags" : ["error""pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}{"type" : "log""@timestamp":"2026-05-18T11:21:53Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:53Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7,"message" : "No living1 {"type" : "log"connections'"}"@timestamp" : "2026-05-18T11:21:53Z", "tags" : ["error"ins",,"plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLivingconnections"}kibanaticsearch"1 {"type": "log", "@timestamp": "2026-05-18T11:21:54Z", "tags" : ["error", "elas"data"], "pid" :7,"message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}1 {"type": "log","@timestamp" : "2026-05-18T11:21:56Z", "tags" : ["warning"asticsearch", "data"],"pid":7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibanains"1 {"type": "log"!"@timestamp": "2026-05-18T11:21:56Z""tags" : ["error", "plug, "taskManager","taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log""@timestamp": "2026-05-18T11:21:56Z", "tags" : ["error", "elasticsearch", "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana1 {"type" : "log""@timestamp": "2026-05-18T11:21:58Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:21:59Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibana1 {"type" : "log"!ins","@timestamp": "2026-05-18T11:21:59Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:21:59Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktopo View ConfigEnable WatchHomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil VasilevP. Galya Dimitrova ELe Todor Stamatov "Ndi. Mario Georgiev. Nikolay Ivanov4o James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y... OAppsJira CloudToastSupport Daily • in 39 m100% <78• Mon 18 May 14:21:59Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files+Lukas Kovalik 2:Today ~ок, сега ще го погленданяма общо с този feature, но все пакможе ли да се логнешCleanShot 2026-05-18 at [EMAIL] ~Update your information::LANGUAGES SPOKEN DURING CALLSDEFAULT SPOKEN LANGUAGEEnglish (United States)|Il the language isn't detected we'll default to this one© Add languageCONNECT/SYNC SETTINGSImport Email Conversations'OG Sign in with GoogleLet's Get Started!не ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОMessage Nikolay Yankov+Aa...
|
52890
|
NULL
|
NULL
|
NULL
|
|
52894
|
1855
|
34
|
2026-05-18T11:21:59.740223+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103319740_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7673782238848625796
|
-8646559087753982588
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
PhostormProi Project: faVsco.js, menu
master, menu
PhostormProiectVIewINavigareCodeLaravelKeractorJOOISFV faVsco.js°9 master k› D ConferenceHandlerv D [EMAIL]© ConferenceCallbackHandler.phpConferenceManager.phpDDIOC Event>D Exceptione Job>W ResolvelService,DVOc)wilioconstants.onoc)TwiioReoositorv.onoUoloaden7 UriGeneratorD UtilityM UuidIM WaveformM Wehhookeh WorkflowM ConfiaurationD ConsoleM Commande>@ ActivitiesD) Analytics)mCnlondarev0 erm> D Hubspot• IntegrationApp> D Traitsc) AddLavoutEntities.phpc) AutoloaDelavedcommand.pho© BackfillOpportunityUserFromAccount(C3ullhorncommandAostract.onoC) BullhornPinaCommand.ohvC) BullhornSearchCommand.onvC) BullhornSessionCommand.ohv@ CheckActivityLoqgableCommand.php 338© CleanDuplicateFieldDataCommand.oh1339C) [EMAIL]@ LoaActivitiesCommand.ohn© ManageSyncStrategyCommand.php342.C) MatchCrmOhiectsCommand.nhn13431C) Match@nnortunitvActivitiesCommand344(C) MiarateProvider nhnlC) [EMAIL]© SoftPhoneManager.php x© TextMessagingService.phpfinal readonly class SoftPhoneManager implements ConferenceManagerprivate tuncclolcreateInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Aopitnereformat: 'Sorry, dialing %s is not available with your subscription.Please contact your manager to enable additional destinations.',values: Sregion ?? ' this number',=custom.log= laravel.log« SF jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X# console [euyA console [STAGING](c DurcoDolatod@nnortunitiacCommandlc DocotGovornorl imite nhnl(@) SendNotLoaged.phpSetupActivityTypeForFollowUp.php),$lead = $account = $opportunity = $contact = $stage = null:try fScrmService = Sthis->crmProviderRegistry->get($room0wner->getTeam->cr Accept iRefeot$crmService->setUser(Sroom0wner);573575576578579580$crmResolver = app( abstract: CrmOwnerResolver::class, ['team' => Sroomdwner->aetTeamo."intearationAdmin' => Sroomdwner.'providerStuo' => Sroomdwner->aetTeamO->aetCrmConfiaurationO->getProviderNameO.I):$crmService = ScrmResolver->prepareCrmServiceO:[$lead, Saccount, Sopportunity, $contact, $stage] = $crmService->matchByPhone(Scallentd.582584585586-587588589590$roomOwner->getIdO592} catch (\Throwable $throwable) {$this->logger->errorC__METHOD': crm exception', [=> $throwable,|D);594596// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happeni/** @var Models\Activitu Sactivitu *Sactivity = Sroom0wner-›activities(-›create(l'tyne"=> Models Activitv::TYPE SOFTPHONE INBOUND!690.601602603'Leadid''contact id'= Models ACtIVITV: : PROVIDER TWEDCON=> Steam->crm id.=> Slead->id 22 nulu.=> Saccount->id 22 null.= Scontact->id 22 nulu.i= Sonportunitv->id 22 nul1.= Sstage->id 22 nuli.=> Models\Activity::STATUS_RINGING,→ Models Activitv• •RECORNTNG NESI606—607608-689610[611= Sthis->ae+VoiceRecordinaReasonfodeSteam.ScallenTdol.612613615/** evar Modeis SessionAccept File 38-X Reject File 4%€ + 1 of 2 files →617hac heon rectored /l Pollback II Confiaure (2 minutes aao)Tx: AutovSo jiminny vCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN' (owner)' ELSE' END) AS USer_1041 A1 A40 V65 ^sa.*t.owner_id FROM social_accounts saJoun usens u on u.id e sa.sociable idiJOIN teams t 1..n<->1: on t.id = u.team_idWHERE u.team_id = 581 and sa.provider = 'salesforce':SELECT * FROM automated_report_results order by id desc;select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556:select * from automated_reports:where id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044,["pdf" "podcast"]SELECT * FROM automated report results WHERE uuid to bin( '822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;select * from automated report resultsorder by id desc;SELECT * FROMWHERE id = 1919:select * fromautomated report results WHERE report id = 54:select * from opportunities where id = 7594349:SELECT * FROM teams WHERE name LIKE '%Lesg': # 711. 692. 16067-jiminnvintegration0lesmills.comselect * from playbooks where team_id = 711; # event 226147SELEd * FROM Dlavbook catedonies WHERE Dlavbook 1d = 55151SELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event':SELECT * SROM eom fields WHEREI1d = 2261471SELECT * FROM com field values WHERE com field id = 226147:SELECT * FROM crm_configurations WHERE id = 692SELECTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "• END) AS user_id,* ounen id EPOM cocial accounte c.IOTN ucene non uid = ca cociable ioJOIN teams t 1..n<->1: on t.id = u.team idWHERE U.team_id = 711 and sa.provider = 'salesforce";SELECT * FROM crm profiles cp JOIN users u 1..n<->1: on u.id = co.user id WHERE u.team_id = 711:select * from leadsselect * from calendarsSELECT• suppont Dally • In 35 m100% Lz• Mon 18 May 14:21:59AskJiminnyReportActivityServiceTest vCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+0 ..• php -l /Users/lukas/jiminny/app/app/Services/Telephony/TextMessagingService.phpzsh:: comnand not tound: ongTnoughtsInoughttor is>I've successfully implemented the fallback token logic for Twilio calls to match the existing dialer pattern. Here's what wasSummary of Changes1. SoftPhoneManager.php• Added import: crmuwnerkesolven• Outbound callis (createdutboundAct ivity method)• Replaced direct CRM service user setting with CrmOwnerResolverl•If fallback fails, falls back to original behavior (team owner or user)• Added error logaina for fallback failures• Inbound calls (createInboundActivity method)• Renlaced direct CRM service user setting with CrmlwnerRecolverl•Maintains existing exception handling for CRM failures• Added import: CrmOwnerResolven• buildActivity method•Replaced direct CRM service user setting with CrmOwnerResolver•|f falllback fails and CRM is not required, falls back to team ownen• If CPM is reauired and fallback fails re-throws excention•Replaced direct CRM service user setting with CrmOwnerResolver• |f rallback fails and CRM is not required, falls back to team ownen•If CRM is required and fallback fails, captures exception and returns user's country codeHow It WorksThe imolementation uses the existing CrmOwnerResolver class which:1. First tries the intearation admin's CRM connection2.If that fails with SocialAccountTokenTnvalidFycention. sparches for team members with active CRM connections3. Orders candidates by role (owner, admin, manager, other users)4. Tries each candidate until findina one with a valid connection6 K oll foil Abrowe tho cricinol evcontiony/ • TextMessagingService.php +30-5Ask anvthina (884-L)Reiect alllAccent alliWN Windsurf Toams 220-12 UTF.8io 4 spaces...
|
52892
|
NULL
|
NULL
|
NULL
|
|
52895
|
1854
|
30
|
2026-05-18T11:22:02.360513+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103322360_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.016666668,"height":0.02111111},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.02111111},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.025555555},"on_screen":false,"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.0,"top":0.0,"width":0.014583333,"height":0.025555555},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false}]...
|
7953126764475839635
|
8095951852832531081
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52896
|
1855
|
35
|
2026-05-18T11:22:02.391760+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103322391_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.007978723,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"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.27027926,"top":1.0,"width":0.006981383,"height":0.0},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\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.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.47573137,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.4867021,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.51329786,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5242686,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.70611703,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-5879124168484268870
|
8095951852832531081
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52898
|
1855
|
37
|
2026-05-18T11:22:08.166600+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103328166_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
41
1
40
65
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993
SELECT * FROM users WHERE id = 25061;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 994;
SELECT * FROM crm_profiles WHERE user_id = 25061;
select * from crm_configurations where id = 834;
SELECT * FROM teams WHERE id = 882;
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 = 882 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;
SELECT * FROM contacts where crm_configuration_id = 834;
SELECT * FROM opportunities WHERE team_id = 933
# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');
AND id IN (8482561,18352941,19042734,19232139,19445140,19472541);
SELECT * FROM opportunity_contacts
WHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 485; #
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
select crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id
where crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')
# and l.converted_at IS NOT NULL
;
# [PASSWORD_DOTS]
SELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')
and opportunity_id IS NULL
order by id desc;
SELECT * FROM teams WHERE id = 604; # 598
SELECT * FROM activities WHERE id = 74410828; # [EMAIL]
SELECT * FROM accounts WHERE id = 20068382;
SELECT * FROM accounts WHERE id = 35186038;
SELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;
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 = 559 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;
select * from sidekick_settings where team_id = 781;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100
SELECT * FROM crm_layouts WHERE crm_configuration_id = 711;
SELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL
and is_internal = 0 and status = 'completed'
order by id desc;
SELECT * FROM crm_layout_entities
WHERE crm_layout_id IN (2352, 2353);
;
SELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;
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 = 556 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;
SELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;
select * from contacts
where crm_configuration_id = 530
and crm_provider_id = 872252;
select * from activities where crm_configuration_id = 530
and user_id = 14343 and type like '%softphone%'
and created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);
SELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t
JOIN crm_configurations c ON t.id = c.team_id
WHERE t.status = 'active';
SELECT * FROM teams where id = 1091;
SELECT * FROM crm_configurations where team_id = 1091;
SELECT * FROM activity_providers where team_id = 1091;
SELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT * FROM teams WHERE name LIKE '%Leadventure%';
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 = 1091 and sa.provider = 'salesforce';
SELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812
SELECT * FROM teams where id = 862;
SELECT * FROM crm_configurations where team_id = 862;
SELECT * FROM activity_providers where team_id = 862;
SELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT t.id, crm.id, crm.provider, ap.* FROM teams t
join crm_configurations crm on t.id = crm.team_id
join activity_providers ap on t.id = ap.team_id
where t.status = 'active' and ap.is_enabled = 1
and crm.provider = 'hubspot'
and ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',
'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');
SELECT * FROM teams where id = 1068;
SELECT * FROM crm_configurations where team_id = 1068;
SELECT * FROM activity_providers where team_id = 1068;
SELECT * FROM activities a
where crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')
and a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'
)
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by a.id desc;
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 = 1068 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262
SELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;
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 = 882 and sa.provider = 'hubspot';
select * from crm_layouts where crm_configuration_id = 834;
select * from crm_layout_entities where crm_layout_id = 2780;
select * from crm_fields where id IN (321153,321192,321193,321194);
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
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 = 1057 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
SELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8
SELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20
SELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10
SELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2
# [PASSWORD_DOTS]
SELECT * FR...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.007978723,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"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.27027926,"top":1.0,"width":0.006981383,"height":0.0},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\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.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.47573137,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.4867021,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.51329786,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5242686,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.70611703,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"41","depth":4,"bounds":{"left":0.6761968,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.6878325,"top":0.123703115,"width":0.00731383,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"40","depth":4,"bounds":{"left":0.69714093,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"65","depth":4,"bounds":{"left":0.7094415,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.72140956,"top":0.12210695,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.7287234,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-01-01';\nand id IN (32415, 32416);\n# and id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;\n\nSELECT * FROM activities WHERE uuid_to_bin('67cebfc2-ed56-44a2-8c68-7a0286ed8618') = uuid; # 79763436\n\nSELECT email_provider_id, COUNT(*) as count, GROUP_CONCAT(id) as ids, GROUP_CONCAT(status) as statuses\nFROM text_relays\nWHERE email_provider_id IN ('19e2027868a64b42', '19e2033ed8ea6b10')\nGROUP BY email_provider_id;\nSELECT id, status, telephony_provider_id, created_at\nFROM activities\nWHERE id IN (80028719, 80028846);\nSELECT id, status, code, email_sent_at, created_at, updated_at\nFROM text_relays\nWHERE id IN (32415, 32416);\nSELECT id, status, code, sender, recipient, created_at\nFROM text_relays\nWHERE sender LIKE '%mario.georgiev%' OR sender LIKE '%stoyan.tomov%'\nORDER BY created_at DESC\nLIMIT 10;\n\nSELECT id, uuid, status, code, sender, recipient, created_at, updated_at\nFROM text_relays\nWHERE uuid = uuid_to_bin('0626141c-27a6-4d8c-aff8-7c8020a2c656');\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nselect * from teams where id = 1;\n\nselect * from roles;","depth":4,"on_screen":true,"value":"SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-01-01';\nand id IN (32415, 32416);\n# and id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;\n\nSELECT * FROM activities WHERE uuid_to_bin('67cebfc2-ed56-44a2-8c68-7a0286ed8618') = uuid; # 79763436\n\nSELECT email_provider_id, COUNT(*) as count, GROUP_CONCAT(id) as ids, GROUP_CONCAT(status) as statuses\nFROM text_relays\nWHERE email_provider_id IN ('19e2027868a64b42', '19e2033ed8ea6b10')\nGROUP BY email_provider_id;\nSELECT id, status, telephony_provider_id, created_at\nFROM activities\nWHERE id IN (80028719, 80028846);\nSELECT id, status, code, email_sent_at, created_at, updated_at\nFROM text_relays\nWHERE id IN (32415, 32416);\nSELECT id, status, code, sender, recipient, created_at\nFROM text_relays\nWHERE sender LIKE '%mario.georgiev%' OR sender LIKE '%stoyan.tomov%'\nORDER BY created_at DESC\nLIMIT 10;\n\nSELECT id, uuid, status, code, sender, recipient, created_at, updated_at\nFROM text_relays\nWHERE uuid = uuid_to_bin('0626141c-27a6-4d8c-aff8-7c8020a2c656');\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nselect * from teams where id = 1;\n\nselect * from roles;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-1262495307487737336
|
957587847100412741
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
41
1
40
65
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993
SELECT * FROM users WHERE id = 25061;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 994;
SELECT * FROM crm_profiles WHERE user_id = 25061;
select * from crm_configurations where id = 834;
SELECT * FROM teams WHERE id = 882;
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 = 882 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;
SELECT * FROM contacts where crm_configuration_id = 834;
SELECT * FROM opportunities WHERE team_id = 933
# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');
AND id IN (8482561,18352941,19042734,19232139,19445140,19472541);
SELECT * FROM opportunity_contacts
WHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 485; #
SELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
select crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id
where crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')
# and l.converted_at IS NOT NULL
;
# [PASSWORD_DOTS]
SELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')
and opportunity_id IS NULL
order by id desc;
SELECT * FROM teams WHERE id = 604; # 598
SELECT * FROM activities WHERE id = 74410828; # [EMAIL]
SELECT * FROM accounts WHERE id = 20068382;
SELECT * FROM accounts WHERE id = 35186038;
SELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;
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 = 559 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;
select * from sidekick_settings where team_id = 781;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100
SELECT * FROM crm_layouts WHERE crm_configuration_id = 711;
SELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL
and is_internal = 0 and status = 'completed'
order by id desc;
SELECT * FROM crm_layout_entities
WHERE crm_layout_id IN (2352, 2353);
;
SELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;
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 = 556 and sa.provider = 'hubspot';
SELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;
SELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;
select * from contacts
where crm_configuration_id = 530
and crm_provider_id = 872252;
select * from activities where crm_configuration_id = 530
and user_id = 14343 and type like '%softphone%'
and created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya
SELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);
SELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t
JOIN crm_configurations c ON t.id = c.team_id
WHERE t.status = 'active';
SELECT * FROM teams where id = 1091;
SELECT * FROM crm_configurations where team_id = 1091;
SELECT * FROM activity_providers where team_id = 1091;
SELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT * FROM teams WHERE name LIKE '%Leadventure%';
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 = 1091 and sa.provider = 'salesforce';
SELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812
SELECT * FROM teams where id = 862;
SELECT * FROM crm_configurations where team_id = 862;
SELECT * FROM activity_providers where team_id = 862;
SELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')
and provider NOT IN ('hubspot', 'aircall')
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by id desc;
SELECT t.id, crm.id, crm.provider, ap.* FROM teams t
join crm_configurations crm on t.id = crm.team_id
join activity_providers ap on t.id = ap.team_id
where t.status = 'active' and ap.is_enabled = 1
and crm.provider = 'hubspot'
and ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',
'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');
SELECT * FROM teams where id = 1068;
SELECT * FROM crm_configurations where team_id = 1068;
SELECT * FROM activity_providers where team_id = 1068;
SELECT * FROM activities a
where crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')
and a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'
)
# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'
order by a.id desc;
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 = 1068 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;
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 = 933 and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262
SELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;
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 = 882 and sa.provider = 'hubspot';
select * from crm_layouts where crm_configuration_id = 834;
select * from crm_layout_entities where crm_layout_id = 2780;
select * from crm_fields where id IN (321153,321192,321193,321194);
SELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
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 = 1057 and sa.provider = 'hubspot';
SELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
SELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;
# [PASSWORD_DOTS]
SELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8
SELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20
SELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last
SELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10
SELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;
SELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2
# [PASSWORD_DOTS]
SELECT * FR...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
52899
|
1854
|
31
|
2026-05-18T11:22:17.492826+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103337492_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.016666668,"height":0.02111111},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.02111111},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.025555555},"on_screen":false,"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.0,"top":0.0,"width":0.014583333,"height":0.025555555},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\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}]...
|
-4611779653030897999
|
8095951852832531081
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute...
|
52895
|
NULL
|
NULL
|
NULL
|
|
52900
|
1855
|
38
|
2026-05-18T11:22:17.465376+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103337465_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.007978723,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"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.27027926,"top":1.0,"width":0.006981383,"height":0.0},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\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.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.47573137,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.4867021,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.51329786,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5242686,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7789402070378785287
|
8095951852832531081
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground...
|
52898
|
NULL
|
NULL
|
NULL
|
|
52901
|
1855
|
39
|
2026-05-18T11:22:20.314199+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103340314_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.007978723,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.00731383,"height":0.0},"on_screen":false,"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.27027926,"top":1.0,"width":0.006981383,"height":0.0},"on_screen":false,"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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\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.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.47573137,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.4867021,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.51329786,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5242686,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.70611703,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
3133187995428949158
|
8095951852832531081
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
53067
|
1858
|
20
|
2026-05-18T11:32:55.416869+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103975416_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82{"type" : "log"asticsearch", "data"], "pid" :7,"@timestamp": "2026-05-18T11:32:49Z","tags" : ["warning"connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11: 32:49Z", "tags"["warning"asticsearch", "data"],"pid":7,"message": "No livingconnections "}I {"type" : "log", "@timestamp" : "2026-05-18T11:32:49Z""tags": ["warning'"licensing"], "pid":7, "message" : "License informationcould not be obtained fromasticsearchto Error: No Livingconnections1 {"type" : "log""@timestamp": "2026-05-18T11:32:49Z","tags" : ["warning"asticsearch", "monitoring"], "pid" :7, "message": "Unable torevive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:32:49Z" , "tags" : ["warning", "elasticsearch", "monitoring"],"pid" :7,"message": "No living connections"}1 {"type" :"1og""@timestamp": "2026-05-18T11:32:49Z""tags" : ["warning","licensing"],"message": "Licenseinformation could not be obtained from Elasticsearch due to Error: No Livingconnections1 {"type": "log""@timestamp": "2026-05-18T11:32:50Z","tags" : ["error", "elasticsearch",,"data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}ticsearch"1 {"type": "log"!,"@timestamp" : "2026-05-18T11:32:50Z", "tags" : ["error","data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}1 {"type": "log","@timestamp":"2026-05-18T11:32:51Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:32:51Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:32:51Z", "tags" : ["error", "taskManager", "taskManager"], "pid" :7, "message" : "Failed to pollfor work: Error: NoLiving connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:32:53Z""tags" : ["error", "elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type" : "log""@timestamp":"2026-05-18T11:32:54Z""tags": ["warning"asticsearch", "data"], "pid" :7, "message" : "Unableto revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:32:54Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7,"message": "No living connections"}1 {"type" : "log".,"@timestamp": "2026-05-18T11:32:54Z","tags" : ["error", "plug, "taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}View in Docker Desktop• View Config•HomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil VasilevGalya DimitrovaLe Todor Stamatov "N. Mario GeorgievNikolay IvanovLo James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y...AppsJira CloudToastSupport Daily • in 28 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:8• Mon 18 May 14:32:556 0O Files+Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMГТОТОВОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
NULL
|
-3186508365840721323
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82{"type" : "log"asticsearch", "data"], "pid" :7,"@timestamp": "2026-05-18T11:32:49Z","tags" : ["warning"connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11: 32:49Z", "tags"["warning"asticsearch", "data"],"pid":7,"message": "No livingconnections "}I {"type" : "log", "@timestamp" : "2026-05-18T11:32:49Z""tags": ["warning'"licensing"], "pid":7, "message" : "License informationcould not be obtained fromasticsearchto Error: No Livingconnections1 {"type" : "log""@timestamp": "2026-05-18T11:32:49Z","tags" : ["warning"asticsearch", "monitoring"], "pid" :7, "message": "Unable torevive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:32:49Z" , "tags" : ["warning", "elasticsearch", "monitoring"],"pid" :7,"message": "No living connections"}1 {"type" :"1og""@timestamp": "2026-05-18T11:32:49Z""tags" : ["warning","licensing"],"message": "Licenseinformation could not be obtained from Elasticsearch due to Error: No Livingconnections1 {"type": "log""@timestamp": "2026-05-18T11:32:50Z","tags" : ["error", "elasticsearch",,"data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}ticsearch"1 {"type": "log"!,"@timestamp" : "2026-05-18T11:32:50Z", "tags" : ["error","data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200*}1 {"type": "log","@timestamp":"2026-05-18T11:32:51Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:32:51Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:32:51Z", "tags" : ["error", "taskManager", "taskManager"], "pid" :7, "message" : "Failed to pollfor work: Error: NoLiving connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:32:53Z""tags" : ["error", "elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}1 {"type" : "log""@timestamp":"2026-05-18T11:32:54Z""tags": ["warning"asticsearch", "data"], "pid" :7, "message" : "Unableto revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:32:54Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7,"message": "No living connections"}1 {"type" : "log".,"@timestamp": "2026-05-18T11:32:54Z","tags" : ["error", "plug, "taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}View in Docker Desktop• View Config•HomeDMsActivityFilesLaterMore-Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil VasilevGalya DimitrovaLe Todor Stamatov "N. Mario GeorgievNikolay IvanovLo James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y...AppsJira CloudToastSupport Daily • in 28 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:8• Mon 18 May 14:32:556 0O Files+Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMГТОТОВОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
53065
|
NULL
|
NULL
|
NULL
|
|
53068
|
1859
|
28
|
2026-05-18T11:32:56.393508+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103976393_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-2796147080355312063
|
-8636637127315567163
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
PhpStormVIewINavigarecodeFV faVsco.js°9 master kProiect v› D ConferenceHandlerv D [EMAIL]© ConferenceCallbackHandler.phpConferenceManager.php>ODTOC7 Event>D ExceptionO JobResolveiService,DVOc)wilioconstants.onoc)TwiioReoositorv.onoUoloaden7 UriGeneratorD UtilityM UuidN WaveformN WehhooksWorkflow> M ConfiaurationD ConsoleD Commands>@ ActivitiesD) Analytics)mCnlondarevm Crm>@ Hubspot>C IntegrationAppServicesTОC 0xv M DatabasevAEUA console 4 s#liminnvAlocalhoctA SPA HS_localA PRODA console 4 sA STAGING& console, NoshorLaravelKeractorJOOISWindow© ActivityController.phpC.BaseService.onp© SoftPhoneManager.php X© TextMessagingService.phpfinal readonly class SoftPhoneManager implements ConferenceManagerprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\A55305"Sorry, dialing %s is not available with your subscription.'Please contact your manager to enable additional destinations.',«values: Sregion ?? ' this number',$lead = $account = Sopportunity = $contact = $stage = null;try {$crmResolver = app( abstract: Crm0wnerResolver::class, [ream = sroomuwner->qerleamor"inteqratzonAdmin' => Sroomiwneri'providerStua => Sroombwner->qetTeamo->getcrmconfzqurationo->getProviderNameOScrmService = ScrmResolver->prepareCrmService@:slead, saccount. Soonortunitv. Scontact, Sstagel = ScrmService->matchBvPhonedScallerid.SroomOwner->aetidocatchThrowable Sthrowable)$this->logger->errorC__METHOD'exceptiof' 1i 2edirsowabl v Accept File 2+': crm exception', [X Reject File 0%@OutputGid jiminny_jupiter.users xd W 1rowvG00Xu sync emarusync dialerJ sunc conferenceJ crm reauiredim nudaes sent at<nul1>conference join reminderI created_at( updated at2024-07-04 08:09:022025-02-03 15:09:34Mactivity action itemsM slack_ follow_up=custom.log= laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]& console [PROD]# console [euyA console [STAGING] X556558.563564565567568569573575=577579Tx: Autovere cri couT LuuraqionE Tanu UEULaVUUUK LE WO:Go jiminny_jupiterBIS BIS XUAYselect * from teams:SELECT r.* FROM automated_reports rjoin teams t on r.team..id = t.idWHERE r.freguency = 'daily'andn status = 1lAND t.status = 'active'AND (r.expires_at >= now OR r.expires_ at IS NULL);select * from automated_report_results where report id IN (18, 33):select * from users where team_id = 1 and id = 1047;SELECT * FROM social_accounts WHERE sociable_id = 1047;select x Tron aculvity searches where 10 = 10752select * from activity search_ filters where activity search_id = 10932:select * tromorder by 10 descorder by id desc;automated reports where 10 IN (55)results where id IN (81):select * from users where id IN (10633. 13987. 11985):|* from users where group id IN (3710):SELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;SELECT * FROMIautomated_report_results WHERE uuid_to_bin( 582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;select * from teams:• suppont Dally • In 2om100% 1• Mon 18 May 14:32:56U AskJiminnyReportActivityServiceTest vCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token ra+0 ..77 tasks doneFixed the try-catch block structure in lextmessagingservice. The issue was that the catch block tor SocialAccountTokenInvalidException (line 147) had no matching try block - the CRM usage code wasn't wrapped in a try block after I added theFinal Implementation summary:1. SoftPhoneManager.php - Added CrmOwnerResolver fallback for both outbound and inbound Twilio calls2. TextMessagingService.php - Added CrmOwnerResolver fallback for both buildActivity and convertCustomerToCousoth implementations now:•First try crmownerReso lver to tind an active salestorce token from the organization• If that tails. tall back to the oricinal direct user assianment nattern•Let existing outer catch blocks handle any SocialAccountTokeninvalidException by setting Ckv data to nullThis ensures Twilio calls will use another active Salesforce token when the admin token expires, preventing "Unknowncustomer issues.Tlle with changes yapp/Component/Twilio/Conference/ConferenceManager/D SoftPhoneManager.php +20-7Ask anvthina (%4L)+ <>Code swe.telView allReject allAccept alleSV v]W Windsurf Teams 320:50 UTF-8 # 4 spaces...
|
53066
|
NULL
|
NULL
|
NULL
|
|
53069
|
1859
|
29
|
2026-05-18T11:32:59.406752+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103979406_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7429716278976468786
|
-8636355650190325311
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
PhpStormViewINavigareCodeLaravelRefactorJOOISWindowFV faVsco.js°9 master kProiect© ActivityController.phpC BaseService.php© SoftPhoneManager.php X>@ ConferenceHandlerv M Conterencemanage,© TextMessagingService.php© SoftPhoneManager.ong© ConferenceCallbackHandler.phpConferenceManager.php>ODTOC Event> 0 Exceptione Jobfinal readonly class SoftPhoneManager implements ConferenceManagerA9V1AVprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\A55format: 'Sorry, dialing %s is not available with your subscription.'' Please contact your manager to enable additional destinations.',"Values: Sregion ??' this number',>W ResolvelW Service,DVO$lead = $account = $opportunity = $contact = $stage = null;c)wilioconstants.onoc)TwiioReoositorv.onoUoloaden7 UriGeneratortryt$crmResolver = app( abstract: Crm0wnerResolver::class, ['team' => $roomOwner->getTeam(),D UtilityM UuidN Waveformn Wehhooks'providerSlua' => SroomOwner->getTeam()->qetCrmConfiqurationO->qetProviderName@Somservice + SereResotVver-spreparecmsenvzee 0):h Workflow> M Confiauration[slead, Saccount, Sopportunity, $contact, Sstage] = ScrmService-›natchByPhone(D ConsoleScallerid.D Commands>@ ActivitiesSroomQwnen->aetIdOD) Analytics)mCnlondarevm Crm>C Hubspot329} catch (\Throwable $throwable) 1$this->logger->error C__METHOD__ . ': crm exception', t"pycention' => Sthoowahl.p› IntegrationAppD);Local ChangesShelLogChanaes 5 filesE env.local [EMAIL] app/Console/Commands< → ® Side-by-side viewer -@cb4ebf0c config/logging.phpDo not ianoreySoftPhoneManager.php app/Component/Twilio/Conference/ConferenceMar(C) TextMessacinaService.oho aoo/Services/Telephonvv Unversioned Files 9 files= env.nikillocal anniE .env.other app© CanAccessAiReportsTest.php tests/Unit/Policies@ CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ro) favicon.ico nublidE ids.txt appTraw_sqL_query.sql [EMAIL] app/Console/Commands/Crm/HubspotM+ WEBHOOK_FILTERING_IMPLEMENTATION.md app'level' => env('LOG _LEVEL', 'info'),'path' => storage_path('logs/Laravel.log').=custom.log= laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]A console [STAGING] X556565568570573-575- 576=577578579Tx: AutovTe cri CouT LuuraqOnuE TanU UE ULaVUUUK LUE 1D:select * from teams:SELECT r.* FROM automated_reports rjoin teams t on r.team..id = t.idWHERE r.freguency = 'daily'and r.status = 1AND t.status = 'active'AND (r.expires_at >= now OR r.expires_ at IS NULL);select * from automated_report_results where report id IN (18, 33):select * from users where team_id = 1 and id = 1047;SELECT * FROM social_accounts WHERE sociable_id = 1047;select x Tron aculvity searches where 10 = 10752select * from activity search_ filters where activity search_id = 10932:select * tromorder by 10 descorder by id desc;automated reports where 10 IN (55results where id IN (81):select * trom users where 1d IN 00055,15787,11985011select * trom users where qroup 10 In (5/0):SELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;SELECT * FROMIautomated_report_results WHERE uuid_to_bin( 582d4b50-8cd3-42a9-9819-d676ff8f3b43) = uuid;select * from teams:• suppont Dally • In 2om100% S2• Mon 18 May 14:32:59U AskJiminnyReportActivityServiceTest v& console [PROD]& console [EU]CascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+O •Go jiminny_jupiterI see the issue - the try-catch structure is broken. The catch block on line 147 for SocialAccountTokenInvalidExceptionmatching try block because the eRM usage code uines 115-146 Is not wrapped in a try block.BISBIS XIA V• TextMessagingService.php7/7 tasks doneFixed the try-catch block structure in Textmessagingservice. The issue was that the catch block tor Socia AccountTokeninvalidException (line 147) had no matching try block - the CRM usage code wasn't wrapped in a try block after I added theFinal Implementation summary:1. SoftPhoneManager.php - Added CrmOwnerResolver fallback for both outbound and inbound Twilio calls2. TextMessagingService.php - Added CrmOwnerResolver fallback for both buildActivity and convertCustomerToCoulnerycode metnoas, with proper try-catch structureBoth imolementations now:• First try CrmOwnerResolver to find an active Salesforce token from the organization•If that fails, fall back to the original direct user assignment pattern• Let existing outer catch blocks handle any Socia AccountTokenInvalidException by settina CRM data to nullThis ensures Twilio calls will use another active Salesforce token when the admin token expires, preventing "Unknowncustomer" issues.Ask anvthina (%4L)+ @code SWE-1.6Current vercion1ditterenceMAAMO'driver' => 'errorlog','level' => env('LOG_LEVEL', 'info'),'path' => storage_path('logs/Laravel.log').'custom channel' => ['driver' => 'single','path' => storage_path('loqs/custom.10g')'level' => env('LOG LEVEL', 'info').W Windsurf Teams 328:49 UTF-8 P. 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
53075
|
1859
|
33
|
2026-05-18T11:33:12.066794+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103992066_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7673782238848625796
|
-8646559087753982588
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
PhpStormView Project: faVsco.js, menu
master, menu
PhpStormViewINavigareCodeLaravelRefactorWindowFV faVsco.js°9 master kProiect© ActivityController.phpC BaseService.php© SoftPhoneManager.php X>@ ConferenceHandlerv Conterencemanage,© TextMessagingService.php© SoftPhoneManager.ong• ConferenceCallbackHandler.phpConferenceManager.php>ODTOC Event> 0 Exceptione Jobfinal readonly class SoftPhoneManager implements ConferenceManagerA9V1AVprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\A55format: 'Sorry, dialing %s is not available with your subscription.'• Please contact your manager to enable additional destinations.',"Values: Sregion ??' this number',>W ResolvelW Service>DVO$lead = $account = $opportunity = $contact = $stage = null;@ TwilioConstants.ohn© TwilioRepository.phpUoloaden7 UriGeneratortry Somnfesotven = ap( abstret: Crmomenfesot ven: oloss, 1'team' => SroomOwner->getTeam(),D UtilityM UuidIM Waveformn Wehhooks'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),Somservice + SereResotVver-spreparecmsenvzee 0):h Workflow> M Confiauration(82e0d, Beriount, Sopporetunaty, Scontact, Sstage) e Sornßervite-natenByPhoneD ConsoleD Commands>@ ActivitiesD) Analytics)mCnlondareSroomQwnen->aetIddvm Crm>@ Hubspot329} catch (\Throwable $throwable) {sthis->logger-serror C_METHOD__': Crm exception',l"pycention' => Sthoowahl.p› IntegrationApp1);Local ChangesLog xChanaes 5 filesE env.local appJiminnyDebugCommand.php app/Console/Commands< → ® Side-by-side viewer -@cb4ebf0c config/logging.phpDo not ianore y'driver' => 'errorlog'SoftPhoneManager.php app/Component/Twilio/Conference/ConferenceMar(C) TextMessacinaService.oho aoo/Services/Telephonv~ Unversioned Files 9 files= env.nikillocal anniE.env.other app© CanAccessAiReportsTest.php tests/Unit/Policies@ CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ro) favicon.ico nublidE ids.txt appTraw_sqL_query.sql [EMAIL] app/Console/Commands/Crm/HubspotM+ WEBHOOK_FILTERING_IMPLEMENTATION.md appLevel → env "Lub Level', "Into)'path' => storage_path('logs/laravel.log').=custom.log= laravel.log« SF jiminny@localhost]4 HS_local [jiminny@localhost]A console [STAGING] X556565568570573-575- 576=577578579Tx: AutovTe cri CouT LuuraqOnuE TanU UE ULaVUUUK LUE 1D:select * from teams:SELECT r.* FROM automated_reports rjoin teams t on r.team..id = t.idWHERE r.freguency = 'daily'and r.status = 1AND t.status = 'active'AND (r.expires_at >= now OR r.expires_ at IS NULL);select * from automated_report_results where report id IN (18, 33):select * from users where team_id = 1 and id = 1047;SELECT * FROM social_accounts WHERE sociable_id = 1047;select x Tron aculvity searches where 10 = 10752select * from activity search_ filters where activity search_id = 10932:select * tromorder by 10 descorder by id desc;automated reports where 10 IN (55results where id IN (81):select * trom users where 1d IN 00055,15787,11985011select * trom users where qroup 10 In (5/0):SELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;SELECT * FROMIautomated_report_results WHERE uuid_to_bin( 582d4b50-8cd3-42a9-9819-d676ff8f3b43) = uuid;select * from teams:suppont Dally • In 2/m100% S2• Mon 18 May 14:33:11U AskJiminnyReportActivityServiceTest v& console [PROD]& console [EU]CascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token Falli+0 ..Go jiminny_jupiterI see the issue - the try-catch structure is broken. The catch block on line 147 for SocialAccountTokenInvalidExceptionmatching try block because the eRM usage code uines 115-146 Is not wrapped in a try block.BIS BIS XUAY• TextMessagingService.php7/7 tasks doneFixed the try-catch block structure in Textmessagingservice. The issue was that the catch block tor Socia AccountTokeninvalidException (line 147) had no matching try block - the CRM usage code wasn't wrapped in a try block after I added theFinal Implementation summary:1. SoftPhoneManager.php - Added CrmOwnerResolver fallback for both outbound and inbound Twilio calls2. TextMessagingService.php - Added CrmOwnerResolver fallback for both buildActivity and convertCustomerToCoulnerycode metnoas, with proper try-catch structureBoth imolementations now:• First try CrmOwnerResolver to find an active Salesforce token from the organization•If that fails, fall back to the original direct user assignment pattern• Let existing outer catch blocks handle any Socia AccountTokenInvalidException by settina CRM data to nullThis ensures Twilio calls will use another active Salesforce token when the admin token expires, preventing "Unknowncustomer" issues.Ask anvthina (%4L)+ @code SWE-1.61ditterenceCurrent vercion'driver' => 'errorlog','level' => env('LOG_LEVEL', 'info').'path' => storage_path('logs/Laravel.log').'custom channel' => ['driver' => 'single','path' => storage_path('loqs/custom.l0g')'level' => env('LOG LEVEL', 'info').W Windsurf Teams 328:49 UTF-8 P 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
53076
|
1858
|
23
|
2026-05-18T11:33:12.623497+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103992623_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82X t1DOCKER (docker-compose)"taskManager""taskManager"], "pid" :7, "message" : "Failed to poll for work: Error: Noconnections"}1 {"type" : "log", "@timestamp": "2026-05-18T11:33:00Z", "tags" : ["error"ticsearch","data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}{"type" : "log","@timestamp" : "2026-05-18T11:33:03Z", "tags" : ["error""pid":7, "message":"[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}{"type" : "log""@timestamp": "2026-05-18T11:33:03Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:03Z", "tags" : ["warning", "elasticsearch", "data"],"pid" :7,"message" : "No living1 {"type" : "log"connections"}"@timestamp" : "2026-05-18T11:33:03Z", "tags" : ["error"ins",,"plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLivingconnections"}kibana{"type": "log", "@timestamp" : "2026-05-18T11:33:05Z"ticsearch","tags" : ["error", "elas"data"], "pid" :7,"message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200"}1 {"type": "log","@timestamp" : "2026-05-18T11:33:06Z", "tags" : ["warning"asticsearch", "data"], "pid":7, "message" : "Unableto revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:06Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibanains"1 {"type": "log"!"@timestamp": "2026-05-18T11:33:06Z""tags" : ["error","plug, "taskManager","taskManager"], "pid" :7, "message" : "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log""@timestamp": "2026-05-18T11:33:08Z", "tags" : ["error", "elasticsearch", "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana{"type" : "log""@timestamp": "2026-05-18T11:33:09Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:33:09Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"I {"type" : "log", "@timestamp" : "2026-05-18T11:33:09Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:33:10Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktop• View ConfigEnable Watch•8• Mon 18 May 14:33:126 0Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil VasilevGalya DimitrovaLe Todor Stamatov "N. Mario Georgiev. Nikolay IvanovLo James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y...AppsJira CloudToastSupport Daily • in 27 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:O Files+HomeDMsActivityFilesLaterMoreSign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMГТОТОВОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
NULL
|
-1866535871199698730
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴82X t1DOCKER (docker-compose)"taskManager""taskManager"], "pid" :7, "message" : "Failed to poll for work: Error: Noconnections"}1 {"type" : "log", "@timestamp": "2026-05-18T11:33:00Z", "tags" : ["error"ticsearch","data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}{"type" : "log","@timestamp" : "2026-05-18T11:33:03Z", "tags" : ["error""pid":7, "message":"[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}{"type" : "log""@timestamp": "2026-05-18T11:33:03Z","tags" : ["warning"asticsearch", "data"], "pid" :7, "message" : "Unable torevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:03Z", "tags" : ["warning", "elasticsearch", "data"],"pid" :7,"message" : "No living1 {"type" : "log"connections"}"@timestamp" : "2026-05-18T11:33:03Z", "tags" : ["error"ins",,"plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLivingconnections"}kibana{"type": "log", "@timestamp" : "2026-05-18T11:33:05Z"ticsearch","tags" : ["error", "elas"data"], "pid" :7,"message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200"}1 {"type": "log","@timestamp" : "2026-05-18T11:33:06Z", "tags" : ["warning"asticsearch", "data"], "pid":7, "message" : "Unableto revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:06Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}kibanains"1 {"type": "log"!"@timestamp": "2026-05-18T11:33:06Z""tags" : ["error","plug, "taskManager","taskManager"], "pid" :7, "message" : "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log""@timestamp": "2026-05-18T11:33:08Z", "tags" : ["error", "elasticsearch", "data"], "pid":7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibana{"type" : "log""@timestamp": "2026-05-18T11:33:09Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:33:09Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7,"message": "No livingconnections"}kibanains"I {"type" : "log", "@timestamp" : "2026-05-18T11:33:09Z""tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:33:10Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktop• View ConfigEnable Watch•8• Mon 18 May 14:33:126 0Jiminny ...Metrotrtencee# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil VasilevGalya DimitrovaLe Todor Stamatov "N. Mario Georgiev. Nikolay IvanovLo James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y...AppsJira CloudToastSupport Daily • in 27 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:O Files+HomeDMsActivityFilesLaterMoreSign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMГТОТОВОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
53077
|
1859
|
34
|
2026-05-18T11:33:14.752444+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103994752_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7429716278976468786
|
-8636355650190325311
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
PhpStormProiect vViewINavigareCodeLaravelRefactorWindowFV faVsco.js°9 master k© ActivityController.phpC BaseService.php© SoftPhoneManager.php X=custom.log= laravel.log« SF jiminny@localhost]4 HS_local [jiminny@localhost]& console [PROD]& console [EU]Cascade>@ ConferenceHandlerv M Conterencemanage,© SoftPhoneManager.ong© ConferenceCallbackHandler.phpConferenceManager.php>ODTOC Event> 0 ExceptionD Job>W ResolvelW Service,DVO@ TwilioConstants.ohn© TwilioRepository.phpUoloaden7 UriGeneratorD UtilityM UuidN Waveformn Wehhooksh Workflow> M ConfiaurationD ConsoleD Commands>@ ActivitiesD) Analytics)mCnlondarevm Crm>C Hubspot› IntegrationApp© TextMessagingService.phpA console [STAGING] XImplement Trial Ownefinal readonly class SoftPhoneManager implements ConferenceManagerA9.1AYprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\A553Tx: AutovGo jiminny_jupiterTe cri CouT LuuraqOnuE TanU UE ULaVUUUK LUE 1D:BIS BIS XUAYformat: 'Sorry, dialing %s is not available with your subscription.'• Please contact your manager to enable additional destinations.',"Values: Sregion ??' this number',556select * from teams:SELECT r.* FROM automated_reports rjoin teams t on r.team..id = t.idWHERE r.freguency = 'daily'and r.status = 1AND t.status = 'active'AND (r.expires_at >= now OR r.expires at IS NULL);$lead = $account = $opportunity = $contact = $stage = null;select * from automated_report_results where report id IN (18, 33):try SormResotver = ppC abstact: CraovnenResotven :olas,'team' => SroomOwner->getTeam(),565select * from users where team_id = 1 and id = 1047:SELECT * FROM social_accounts WHERE sociable_id = 1047;'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),Somservice + SereResotVver-spreparecmsenvzee 0):568570(82e0d, Beriount, Sopporetunaty, Scontact, Sstage) e Sornßervite-natenByPhoneselect x Tron aculvity searches Where 10 = 10752select * from activity search_ filters where activity search_id = 10932:select * tromorder by 10 descorder by id desc;automated reports where 10 IN (55results where id IN (81):SroomQwnen->aetIdd329} catch (\Throwable $throwable) {sthis->logger-serror C_METHOD__': Crm exception',l"pycention' => Sthoowahl.p1);573-575- 576=577578579select * trom users where 1d IN 00055,15787,11 985071Fixina Redis Rate Limit Erronselect * trom users where qroup 10 IN (5/00:SELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;SELECT * FROMIautomated_report_results WHERE uuid_to_bin( 582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;Ask anvthina (%4L)+ @code SWE-1.6select * from teams:Local ChangesLog xChanaes 5 filesE env.local appJiminnyDebugCommand.php app/Console/Commandsphploaqina.ono confidSoftPhoneManager.php app/Component/Twilio/Conference/ConferenceMar(C) TextMessacinaService.oho aoo/Services/Telephonv~ Unversioned Files 9 files= env.nikillocal anniE .env.other app© CanAccessAiReportsTest.php tests/Unit/Policies@ CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ro) favicon.ico nublidE ids.txt appTraw_sqL_query.sql [EMAIL] app/Console/Commands/Crm/HubspotM+ WEBHOOK_FILTERING_IMPLEMENTATION.md app< → ® Side-by-side viewer -Do not ianore y@cb4ebf0c config/logging.phpCurrent vercion'driver' => 'errorlog'Level → env "Lub Level', "Into)'path' => storage_path('logs/laravel.1og'),'driver' => 'errorlog','level' => env('LOG_LEVEL', 'info').'path' => storage_path('logs/Laravel.log')'custom channel' => ['driver' => 'single','path' => storage_path('loqs/custom.10g')'level' => env('LOG LEVEL', 'info')."suppont Dally • In 21m100% S2• Mon 18 May 14:33:14AskJiminnyReportActivityServiceTest vFixing Redis Rate LimSalestorce Token FalliCascade+0 ..Wcascade Code x• ..Kick off a new proiect. Make changes1ditterenceМAMAYW Windsurf Teams 328:49 UTF-8 P 4 spaces ®...
|
53075
|
NULL
|
NULL
|
NULL
|
|
53078
|
1859
|
35
|
2026-05-18T11:33:17.862272+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103997862_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny_jupiter
Sync Changes
Hide This Notification
Code changed:
Hide
19
19
17
Previous Highlighted Error
Next Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.3929521,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.40292552,"top":0.10055866,"width":0.00731383,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.4119016,"top":0.09896249,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.4192154,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.47573137,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.4867021,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.51329786,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5242686,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny_jupiter","depth":4,"bounds":{"left":0.69348407,"top":0.09896249,"width":0.04089096,"height":0.01915403},"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":"19","depth":4,"bounds":{"left":0.6871675,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"19","depth":4,"bounds":{"left":0.6988032,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"17","depth":4,"bounds":{"left":0.71043885,"top":0.123703115,"width":0.00930851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.72140956,"top":0.12210695,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.7287234,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
3512545928479357484
|
8095951577952526985
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny_jupiter
Sync Changes
Hide This Notification
Code changed:
Hide
19
19
17
Previous Highlighted Error
Next Highlighted Error...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
53079
|
1858
|
24
|
2026-05-18T11:33:17.822348+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779103997822_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-4235983745889776938
|
-8204421443435123770
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴2DOCKER (docker-compose)asticsearch", "data"],"message": "No livingconnections"}1 {"type" : "log","@timestamp" : "2026-05-18T11:33:09Z", "tags": ["error","plug, "taskManager", "taskManager"],"pid":7, "message": "Failed to poll.for work: Error: NoLiving connections"}ticsearch"{"type": "log","data"],,"@timestamp":'2026-05-18T11:33:10Z"tags": ["error""pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticseelasticsearch:9200"}{"type" : "log""@timestamp": "2026-05-18T11:33:13Z", "tags" : ["warning"asticsearch","data"], "pid" :7, "message" : "Unablerevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:13Z" , "tags" : ["warning", "elasticsearch", "data"],'"pid":7, "message": "No livingconnections"}kibana1 {"type": "log".,"@timestamp" : "2026-05-18T11:33:13Z", "tags" : ["error", "plugins""taskManager", "taskManager"], "pid" :7, "message": "Failed to poll for work: Error: NoLiving connections"}klbana{"type" : "log", "@timestamp" : "2026-05-18T11:33:13Z" , "tags" : ["warning", "elasticsearch", "data"],"pid" :7,"message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:13Z" , "tags" : ["warning", "elasticsearch", "data"], "pid":7, "message" : "No livingconnections"}kibanains"1 {"type" : "log","@timestamp": "2026-05-18T11:33:13Z""tags" : ["error","reporting", "esqueue","queue-worker"46mdeo -job querying failed: Error: No Living connectionsin"error"], "pid" :7, "message" : "mpau4y7h00070bdf86at sendReqWithConnection(/usr/share/kibana/node_modules/elasticsearch/src/lib/transport.js:266:15)\n(/usr/share/kibana/node_modules/elasticsearch/src/lib/connection_pool.js:243:7)\nprocess._tickCallback (internal/process/next_tick.js:61:11)"}kibana1 {"type" : "log"ticsearch","@timestamp" : "2026-05-18T11:33:13Z", "tags" : ["error","data"],"pid":7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200*}docker_lamp_1kibana{"type" : "log", "@timestamp" : "2026-05-18T11:33:15Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:15Z" , "tags" : ["warning", "elasticsearch", "data"], "pid":7, "message": "No livingconnections"}kibana1 {"type" : "log"!ins","@timestamp": "2026-05-18T11:33:15Z","tags" : ["error","plug,"taskManager""taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}kibana1 {"type": "log", "@timestamp": "2026-05-18T11:33:15Z", "tags" : ["error", "elasticsearch", "data"],"pid" :7, "message": "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}View in Docker Desktop• View ConfigEnable Watch•HomeDMsActivityFilesLaterMoreJiminny ...MetromrtencE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...• Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka StoyanovaStoyan Tomov€. Vasil Vasilev% Galya DimitrovaLa Todor Stamatov "8. Mario Georgiev. Nikolay IvanovLo James Graham *8 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiE. Lukas Kovalik y...AppsJira CloudToastSupport Daily • in 27 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:8• Mon 18 May 14:33:176 0+Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMГТОТОВОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
53076
|
NULL
|
NULL
|
NULL
|
|
53082
|
1860
|
0
|
2026-05-18T11:33:50.084264+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779104030084_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴2XIDOCKER (docker-compose)kibana{"type""log""@timestamp": "2026-05-18T11:33:43Z"ticsearch""data"],"pid" :7,message","tags" : ["error""elas:"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200"}kibana1 {"type" : "log""@timestamp" : "2026-05-18T11:33:45Z", "tags" : ["warning"asticsearch", "data"], "pid" :7,,"el'message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:33:45Z", "tags" : ["warning"asticsearch", "data"],'"message"kibana1 {"type" : "log"connections"}"@timestamp""2026-05-18T11:33:45Z""tags" : ["error"ins", "taskManager"Living connections"}"taskManager"], "pid":7, "message":"Failed to poll for work: Error: Nokibana1 {"type" : "log","@timestamp" : "2026-05-18T11:33:45Z", "tags" : ["error","elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch: 9200*}kibanaticsearch"1 {"type": "log""@timestamp": "2026-05-18T11:33:48Z", "tags" : ["error", "elas, "data"],"pid":7, "message":"[ConnectionError]:getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200"}kibana1 {"type": "log","@timestamp" : "2026-05-18T11:33:48Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:48Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:33:48Z","tags" : ["error","taskManager", "taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:33:49Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:49Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7, "message": "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:33:49Z""tags" : ["warning"ugins","licensing"], "pid" :7, "message" : "License information could not be obtained from Elasticsearch due to Error: No Living connections error"}1 {"type" : "log","@timestamp": "2026-05-18T11:33:49Z", "tags" : ["warning"asticsearch", "monitoring"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:33:49Z", "tags" : ["warning", "elasticsearch", "monitoring"],"pid":7, "message": "No living connections"}1 {"type": "log", "@timestamp": "2026-05-18T11:33:49Z","tags" : ["warning", "plugins","licensing"],"pid":7, "message": "License information could not be obtained from Elasticsearch due to Error: No Living connectionsView in Docker Desktop• View ConfigEnable Watch8• Mon 18 May 14:33:49Jiminny ...Metrorrtence# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...• Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya DimitrovaLa Todor Stamatov ". Mario GeorgievNikolay IvanovLo James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y...AppsJira CloudToastSupport Daily • in 27 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:6 0+HomeDMsActivityFilesLaterMoreSign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMгТОТОвОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
NULL
|
-269239859886645834
|
NULL
|
idle
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DE SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DEV (docker)₴2XIDOCKER (docker-compose)kibana{"type""log""@timestamp": "2026-05-18T11:33:43Z"ticsearch""data"],"pid" :7,message","tags" : ["error""elas:"[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200"}kibana1 {"type" : "log""@timestamp" : "2026-05-18T11:33:45Z", "tags" : ["warning"asticsearch", "data"], "pid" :7,,"el'message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:33:45Z", "tags" : ["warning"asticsearch", "data"],'"message"kibana1 {"type" : "log"connections"}"@timestamp""2026-05-18T11:33:45Z""tags" : ["error"ins", "taskManager"Living connections"}"taskManager"], "pid":7, "message":"Failed to poll for work: Error: Nokibana1 {"type" : "log","@timestamp" : "2026-05-18T11:33:45Z", "tags" : ["error","elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearchelasticsearch: 9200*}kibanaticsearch"1 {"type": "log""@timestamp": "2026-05-18T11:33:48Z", "tags" : ["error", "elas, "data"],"pid":7, "message":"[ConnectionError]:getaddrinfo ENOTFOUND elasticsearchelasticsearch:9200"}kibana1 {"type": "log","@timestamp" : "2026-05-18T11:33:48Z""tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:48Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:33:48Z","tags" : ["error","taskManager", "taskManager"], "pid":7, "message": "Failed to poll for work: Error: NoLiving connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:33:49Z", "tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:33:49Z", "tags" : ["warning", "elasticsearch", "data"],"pid":7, "message": "No living connections"}I {"type" : "log", "@timestamp" : "2026-05-18T11:33:49Z""tags" : ["warning"ugins","licensing"], "pid" :7, "message" : "License information could not be obtained from Elasticsearch due to Error: No Living connections error"}1 {"type" : "log","@timestamp": "2026-05-18T11:33:49Z", "tags" : ["warning"asticsearch", "monitoring"], "pid" :7, "message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:33:49Z", "tags" : ["warning", "elasticsearch", "monitoring"],"pid":7, "message": "No living connections"}1 {"type": "log", "@timestamp": "2026-05-18T11:33:49Z","tags" : ["warning", "plugins","licensing"],"pid":7, "message": "License information could not be obtained from Elasticsearch due to Error: No Living connectionsView in Docker Desktop• View ConfigEnable Watch8• Mon 18 May 14:33:49Jiminny ...Metrorrtence# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...• Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka Stoyanova. Stoyan Tomov€. Vasil Vasilev% Galya DimitrovaLa Todor Stamatov ". Mario GeorgievNikolay IvanovLo James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiLukas Kovalik y...AppsJira CloudToastSupport Daily • in 27 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:6 0+HomeDMsActivityFilesLaterMoreSign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMгТОТОвОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
53080
|
NULL
|
NULL
|
NULL
|
|
53083
|
1861
|
0
|
2026-05-18T11:33:50.986636+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779104030986_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormProiect vViewINavicareCodeLaravelRefactorW PhpStormProiect vViewINavicareCodeLaravelRefactorWindowFV faVsco.js°9 master k© ActivityController.phpC BaseService.php© SoftPhoneManager.php X=custom.log= laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]>@ ConferenceHandlerv M Conterencemanage,© TextMessagingService.phpA console [STAGING] X© SoftPhoneManager.ong• ConferenceCallbackHandler.php© ConferenceManager.php>ODTO•Event> 0 Exceptione Job>W ResolvelW Service,DVO@ TwilioConstants.ohnfinal readonly class SoftPhoneManager implements ConferenceManagerA9.1AYprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\A553Tx: AutovTe cri CouT LuuraqOnuE TanU UE ULaVUUUK LUE WD:format: 'Sorry, dialing %s is not available with your subscription.'' Please contact your manager to enable additional destinations.',"Values: Sregion ??' this number',556select * from teams:SELECT r.* FROM automated_reports rjoin teams t on r.team..id = t.idWHERE r.freguency = 'daily'and r.status = 1AND t.status = 'active'AND (r.expires_at >= now) OR r.expires_at IS NULL);= $contact = $stage = null;select * from automated_report_results where report id IN (18, 33):© TwilioRepository.phpUoloaden7 UrlGeneratorD UtilityM UuidIM Waveformn Wehhooksh Workflow> M ConfiaurationD ConsoleD Commands>@ ActivitiesD) Analytics)mCnlondarevm Crm>C Hubspot› IntegrationApptry Somnfesotven = ap( abstret: Crmomenfesot ven: oloss, 1'team' => SroomOwner->getTeam(),565select * from users where team_id = 1 and id = 1047;SELECT * FROM social_accounts WHERE sociable_id = 1047;|'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),Somservice + SereResotVver-spreparecmsenvzee 0):568570(82e0d, Beriount, Sopporetunaty, Scontact, Sstage) e Sornßervite-natenByPhoneselect x Tron aculvity searches where 10 = 10752select * from activity search_ filters where activity search_id = 10932:select * tromorder by 10 descorder by id desc;automated reports where 10 IN (55results where id IN (81):SroomQwnen->aetIdd329} catch (\Throwable $throwable) {sthis->logger-serror C_METHOD__': Crm exception',l"pycention' => Sthoowahl.p1);573-575- 576=577578579select * trom users where 1d IN 00055,15787,11985011select * trom users where qroup 10 In (5/0):SELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;SELECT * FROMIautomated_report_results WHERE uuid_to_bin( 582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;select * from teams:Local ChangesLog xChanaes 5 filesE env.local appJiminnyDebugCommand.php app/Console/Commandsphploaqina.ono confidSoftPhoneManager.php app/Component/Twilio/Conference/ConferenceMar(C) TextMessacinaService.oho aoo/Services/Telephonv~ Unversioned Files 9 files= env.nikillocal anniE.env.other app© CanAccessAiReportsTest.php tests/Unit/Policies@ CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ro) favicon.ico nublidE ids.txt appTraw_sqL_query.sql [EMAIL] app/Console/Commands/Crm/HubspotM+ WEBHOOK_FILTERING_IMPLEMENTATION.md app<→ E, Side-by-side viewer +Do not ianore y@cb4ebf0c config/logging.phpCurrent vercion'driver' => 'errorlog'Level → env "Lub Level', "1nto)'path' => storage_path('logs/laravel.log'),'driver' => 'errorlog','level' => env('LOG_LEVEL', 'info'),'path' => storage_path('logs/Laravel.log').'custom channel' => ['driver' => 'single','path' => storage_path('loqs/custom.l0g')'level' => env('LOG LEVEL', 'info').• suppont Dally • In 21m100% 2• Mon 18 May 14:33:50AskJiminnyReportActivityServiceTest v& console [PROD]# console [euyCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token FalliEnable SClM Role Mi+0 ..Go jiminny_jupiterrole/permission system to understand the architecture.019 A19 V17 ^ VSearched recorder.*voice|analyst in ~/jiminny/appThought for 1s>Created Todo List 7 tasks1)Analvze current SCIM imolementation and role/permission svstem'Review validation rules for roles and permissions• Design SCIM role assignment schema• Implement role mutator for SCIM• Add validation to SCIM role assignment• Write unit tests for SCIM role managementUpdate scim documentationIhought for 1shought for ZsRead CoreUserRequest.php and 2 other filesSearched ROLE RECORDERROLE VOICEROLE ANALYSTIROLE LISTENER in apo/Models/User.ohoSurfinaAsk anvthina (%4L)+ @code SWE-1.60901ditterenceW Windsurf Toams 228-10 UTF.8io 4 spaces ©...
|
NULL
|
-2077798200752967274
|
NULL
|
idle
|
ocr
|
NULL
|
PhpStormProiect vViewINavicareCodeLaravelRefactorW PhpStormProiect vViewINavicareCodeLaravelRefactorWindowFV faVsco.js°9 master k© ActivityController.phpC BaseService.php© SoftPhoneManager.php X=custom.log= laravel.log4 SF jiminny@localhost]4 HS_local [jiminny@localhost]>@ ConferenceHandlerv M Conterencemanage,© TextMessagingService.phpA console [STAGING] X© SoftPhoneManager.ong• ConferenceCallbackHandler.php© ConferenceManager.php>ODTO•Event> 0 Exceptione Job>W ResolvelW Service,DVO@ TwilioConstants.ohnfinal readonly class SoftPhoneManager implements ConferenceManagerA9.1AYprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\A553Tx: AutovTe cri CouT LuuraqOnuE TanU UE ULaVUUUK LUE WD:format: 'Sorry, dialing %s is not available with your subscription.'' Please contact your manager to enable additional destinations.',"Values: Sregion ??' this number',556select * from teams:SELECT r.* FROM automated_reports rjoin teams t on r.team..id = t.idWHERE r.freguency = 'daily'and r.status = 1AND t.status = 'active'AND (r.expires_at >= now) OR r.expires_at IS NULL);= $contact = $stage = null;select * from automated_report_results where report id IN (18, 33):© TwilioRepository.phpUoloaden7 UrlGeneratorD UtilityM UuidIM Waveformn Wehhooksh Workflow> M ConfiaurationD ConsoleD Commands>@ ActivitiesD) Analytics)mCnlondarevm Crm>C Hubspot› IntegrationApptry Somnfesotven = ap( abstret: Crmomenfesot ven: oloss, 1'team' => SroomOwner->getTeam(),565select * from users where team_id = 1 and id = 1047;SELECT * FROM social_accounts WHERE sociable_id = 1047;|'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),Somservice + SereResotVver-spreparecmsenvzee 0):568570(82e0d, Beriount, Sopporetunaty, Scontact, Sstage) e Sornßervite-natenByPhoneselect x Tron aculvity searches where 10 = 10752select * from activity search_ filters where activity search_id = 10932:select * tromorder by 10 descorder by id desc;automated reports where 10 IN (55results where id IN (81):SroomQwnen->aetIdd329} catch (\Throwable $throwable) {sthis->logger-serror C_METHOD__': Crm exception',l"pycention' => Sthoowahl.p1);573-575- 576=577578579select * trom users where 1d IN 00055,15787,11985011select * trom users where qroup 10 In (5/0):SELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;SELECT * FROMIautomated_report_results WHERE uuid_to_bin( 582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;select * from teams:Local ChangesLog xChanaes 5 filesE env.local appJiminnyDebugCommand.php app/Console/Commandsphploaqina.ono confidSoftPhoneManager.php app/Component/Twilio/Conference/ConferenceMar(C) TextMessacinaService.oho aoo/Services/Telephonv~ Unversioned Files 9 files= env.nikillocal anniE.env.other app© CanAccessAiReportsTest.php tests/Unit/Policies@ CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ro) favicon.ico nublidE ids.txt appTraw_sqL_query.sql [EMAIL] app/Console/Commands/Crm/HubspotM+ WEBHOOK_FILTERING_IMPLEMENTATION.md app<→ E, Side-by-side viewer +Do not ianore y@cb4ebf0c config/logging.phpCurrent vercion'driver' => 'errorlog'Level → env "Lub Level', "1nto)'path' => storage_path('logs/laravel.log'),'driver' => 'errorlog','level' => env('LOG_LEVEL', 'info'),'path' => storage_path('logs/Laravel.log').'custom channel' => ['driver' => 'single','path' => storage_path('loqs/custom.l0g')'level' => env('LOG LEVEL', 'info').• suppont Dally • In 21m100% 2• Mon 18 May 14:33:50AskJiminnyReportActivityServiceTest v& console [PROD]# console [euyCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token FalliEnable SClM Role Mi+0 ..Go jiminny_jupiterrole/permission system to understand the architecture.019 A19 V17 ^ VSearched recorder.*voice|analyst in ~/jiminny/appThought for 1s>Created Todo List 7 tasks1)Analvze current SCIM imolementation and role/permission svstem'Review validation rules for roles and permissions• Design SCIM role assignment schema• Implement role mutator for SCIM• Add validation to SCIM role assignment• Write unit tests for SCIM role managementUpdate scim documentationIhought for 1shought for ZsRead CoreUserRequest.php and 2 other filesSearched ROLE RECORDERROLE VOICEROLE ANALYSTIROLE LISTENER in apo/Models/User.ohoSurfinaAsk anvthina (%4L)+ @code SWE-1.60901ditterenceW Windsurf Toams 228-10 UTF.8io 4 spaces ©...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
53084
|
1860
|
1
|
2026-05-18T11:34:22.414061+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779104062414_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","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}]...
|
7427406631313725685
|
-8132367010325492798
|
idle
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
SlackFileEditViewGoHistoryWindowHelpEU (DOCKER81DOCKER (docker-compose)asticsearch"h:9200/"3, "data"],"pid":7,"message": "UnableDEV (docker)₴2reviveconnection: [URL_WITH_CREDENTIALS] "2026-05-18T11:34:18Z" , "tags" : ["warning"asticsearch", "data"], "pid" :7,"message" : "No livingconnections"}1 {"type": "log"!,"@timestamp": "2026-05-18T11:34:18Z","taskManager""taskManager"], "pid" :7, "message" : "Failed to pollfor work: Error: NoLivingconnections"}kibana{"type": "log""@timestamp": "2026-05-18T11:34:19Z","tags" : ["warning", "elasticsearch", "data"], "pid" :7, "message" : "Unabletorevive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:34: 19Z"asticsearch", "data"],'"pid":7, "message" : "No livingconnections"},"tags" : ["warning", "elkibana{"type" : "log", "@timestamp": "2026-05-18T11:34:19Z", "tags" : ["warning", "plugins""licensing"],"pid":7, "message": "License informationcould not be obtained from Elasticsearch due to Error: No Living connectionskibana1 {"type" : "log""@timestamp": "2026-05-18T11:34:19Z","tags" : ["warning"asticsearch", "monitoring"], "pid" :7, "message" : "Unable tocsearch:9200/"3revive connection: [URL_WITH_CREDENTIALS] : "2026-05-18T11:34:20Z","tags" : ["error""elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch: 9200"}kibanaI {"type" : "log", "@timestamp" : "2026-05-18T11:34:21Z""tags" : ["error", "elasticsearch", "data"], "pid" :7, "message" : "[ConnectionError]: getaddrinfo ENOTFOUND elasticsearch elasticsearch:9200"}kibana1 {"type" : "log","@timestamp": "2026-05-18T11:34:21Z","tags" : ["warning""elasticsearch", "data"], "pid" :7,"message": "Unable to revive connection: [URL_WITH_CREDENTIALS] "2026-05-18T11:34:21Z" , "tags" : ["warning" , "elasticsearch", "data"], "pid":7, "message": "No living connections"}kibana1 {"type" : "log","@timestamp" : "2026-05-18T11:34:21Z", "tags" : ["error", "plugins",, "taskManager",, "taskManager"], "pid" :7, "message" : "Failed to poll for work: Error: NoLiving connections"}View in Docker Desktop• View ConfigEnable Watch•HomeDMsActivityFilesLaterMoreJiminny ...MetromrtencE# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...0 Direct messages. Nikolay YankovR. Aneliya Angelovaão Stefka StoyanovaStoyan Tomov€. Vasil Vasilev% Galya DimitrovaLa Todor Stamatov ". Mario GeorgievNikolay IvanovLo James Graham *2 Stoyan Tanev&. Steliyan Georgiev&e Petko KashinskiE. Lukas Kovalik y...AppsJira CloudToastSupport Daily • in 26 m100% <7Describe what you are looking forNikolay YankovMessagesAdd canvas@ Files• Add language |TodayCONNECT/SYNC SETTINGSImport Email Conversations'OLet's Get Started:8• Mon 18 May 14:34:226 0+Sign in with Googleне ме пускаNikolay Yankov 2:17 PMЕй сегаГОТОВОLukas Kovalik 2:26 PMоще ведньж и в СФNikolay Yankov 2:27 PMГТОТОВОLukas Kovalik 2:27 PMработи вечеNikolay Yankov 2:27 PMимаше ли нещо за фиксLukas Kovalik 2:28 PMтрябва да си вързан към SF да работиNikolay Yankov 2:28 PMaxaaaMessage Nikolay Yankov...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
53085
|
1861
|
1
|
2026-05-18T11:34:23.808360+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779104063808_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.3929521,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"}]...
|
5774539588715192368
|
-8132367147898524734
|
idle
|
hybrid
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
PhpStormProiect vViewINavicareCodeLaravelRefactorWindowFV faVsco.js°9 master k© ActivityController.phpC BaseService.php© SoftPhoneManager.php X=custom.log= laravel.log« SF jiminny@localhost]4 HS_local [jiminny@localhost]& console [PROD]& console [EU]>@ ConferenceHandlerv M Conterencemanage,© SoftPhoneManager.ong• ConferenceCallbackHandler.php© ConferenceManager.php>ODTO•Event> 0 Exceptione Job>W ResolvelW Service>DVO@ TwilioConstants.ohn© TextMessagingService.phpA console [STAGING] Xfinal readonly class SoftPhoneManager implements ConferenceManagerA9.1AYprivate function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\A553Tx: AutovTe cri CouT LuuraqOnuE TanU UE ULaVUUUK LUE 1D:Go jiminny_jupiter019 A19 V17 ^ Vformat: 'Sorry, dialing %s is not available with your subscription.'' Please contact your manager to enable additional destinations.',"Values: Sregion ??' this number',556select * from teams:SELECT r.* FROM automated_reports rjoin teams t on r.team..id = t.idWHERE r.freguency = 'daily'and r.status = 1AND t.status = 'active'AND (r.expires_at >= now) OR r.expires_at IS NULL);= $contact = $stage = null;select * from automated_report_results where report id IN (18, 33):© TwilioRepository.phpUoloaden7 UrlGeneratorD UtilityM UuidN Waveformn Wehhooksh Workflow> M ConfiaurationD ConsoleD Commands>@ ActivitiesD) Analytics)mCnlondarevm Crm>C Hubspot› IntegrationApptry Somnfesotven = ap( abstret: Crmomenfesot ven: oloss, 1'team' => SroomOwner->getTeam(),565select * from users where team_id = 1 and id = 1047:SELECT * FROM social_accounts WHERE sociable_id = 1047;|'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),Somservice + SereResotVver-spreparecmsenvzee 0):568570(82e0d, Beriount, Sopporetunaty, Scontact, Sstage) e Sornßervite-natenByPhoneselect x rron aculvity searches where 10 = 10702select * from activity search filters where activity search_id = 10932:select * tromorder by 10 descorder by id desc;automated reports where 10 IN (55results where id IN (81):SroomQwnen->aetIdd329} catch (\Throwable $throwable) {sthis->logger-serror C_METHOD__': Crm exception',l"pycention' => Sthoowahl.p1);573-575- 576=577578579select * trom users where 1d IN 00055,15787,11 985071select * trom users where qroup 10 In (5/00:SELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;SELECT * FROMIautomated_report_results WHERE uuid_to_bin( 582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;select * from teams:Local ChangesLog xChanaes 5 filesE env.local appJiminnyDebugCommand.php app/Console/Commandsphploaqina.ono confidSoftPhoneManager.php app/Component/Twilio/Conference/ConferenceMar(C) TextMessacinaService.oho aoo/Services/Telephonv~ Unversioned Files 9 files= env.nikillocal anniE.env.other app© CanAccessAiReportsTest.php tests/Unit/Policies@ CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ro) favicon.ico nublidE ids.txt appTraw_sqL_query.sql [EMAIL] app/Console/Commands/Crm/HubspotM+ WEBHOOK_FILTERING_IMPLEMENTATION.md app<→ E, Side-by-side viewer +Do not ianore y@cb4ebf0c config/logging.phpCurrent vercion'driver' => 'errorlog'Level → env "Lub Level', "1nto)'path' => storage_path('logs/laravel.1og'),'driver' => 'errorlog','level' => env('LOG_LEVEL', 'info'),'path' => storage_path('logs/Laravel.log').'custom channel' => ['driver' => 'single','path' => storage_path('loqs/custom.10g')'level' => env('LOG LEVEL', 'info').• suppont Dally • In 20m100% 2• Mon 18 May 14:34:23AskJiminnyReportActivityServiceTest vCascadeImplement Trial OwneFixing Redis Rate LimSalestorce Token FalliSClM Role Manager+0 ..sedrcned class. Kole in ap.inougntror is1Analyze current selm implementation and role permission systemReview validation rules for roles and permissionsiDesign SCIM role assignment schemaImolement role mutator for SCIMAdd validation to SCIM role assianmentWrite unit tests for SCIM role managementUodate SCIM documentationkead scimProvisioning.onp and s otnertlles >Thought for 1s)Thought for 2sSearched ROLE_RECORDER|ROLE_VOICEIROLE ANALYST|ROLE LISTENER in app/Models/User.phpThought for 2sSearched PERMISSION ADMINPERMISSION MANAGER In app/ModelsRead RolesAndCrmOntionMismatchRule.ohdAnalyzed app/Component/SCIM/Mutators/Attributes/UserThought for 1s)Ask anvthina (%4L)+ <>Code sws.e1ditterenceWAAYWN Windsurf Toams 228-10 UTF.8io 4 spaces...
|
53083
|
NULL
|
NULL
|
NULL
|
|
53086
|
1860
|
2
|
2026-05-18T11:34:53.832131+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779104093832_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny_jupiter
Sync Changes
Hide This Notification
Code changed:
Hide
19
19
17
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE id = 1;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;
SELECT * FROM crm_fields WHERE id = 2234;
SELECT * FROM crm_field_values WHERE crm_field_id = 2234;
select * from crm_profiles where user_id = 143;
select * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO
select * from business_processes where crm_configuration_id = 39;
# 01941000000H669AAC, 01941000000H66JAAS
select * from record_type_field_values
where record_type_id IN (24);
select * from crm_field_values where id IN (2730);
select * from crm_configurations where id = 39;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce'; #1035
select * from users where team_id = 1; # 222 group 3
SELECT * FROM activities WHERE user_id = 222 order by id desc;
select * from sidekick_settings where team_id = 1;
select * from teams where id = 1;
select * from team_features where team_id = 1;
select * from activities where crm_configuration_id = 2
and provider = 'ms-teams' and id = 608765;
SELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';
select * from sidekick_settings where team_id = 2;
SELECT * FROM activities WHERE id = 608660;
select * from activity_summary_logs where activity_id = 608660;
select * from ai_prompts where transcription_id = 11214;
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;
# id: 608818, crm: 59628809737
SELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;
# id: 608821, crm: 59632069252
SELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,
playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,
scheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at
FROM activities a
join calendar_events ce on a.calendar_event_id = ce.id
WHERE a.id IN (608818, 608821);
select * from users where team_id = 1;
select * from team_settings where team_id = 1;
select * from crm_profiles where crm_configuration_id = 39 order by user_id;
select * from team_features where team_id = 1;
select * from users where team_id = 2;
SELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639
# Preslava N. Ivanova, grou id 3
SELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;
select * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';
select
a.id,
a.type,
a.scheduled_start_time,
a.actual_start_time,
a.created_at,
a.opportunity_id,
a.status
FROM activities a
WHERE opportunity_id = 344
and status IN ('completed', 'received', 'delivered')
and (
(a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))
;
SELECT * FROM users WHERE id = 222;
SELECT * FROM crm_profiles WHERE user_id = 222;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;
select * from group_deal_risk_types;
select * from opportunities where team_id = 1;
SELECT * FROM opportunities WHERE id = 315;
SELECT * FROM crm_field_data WHERE object_id = 315;
select * from crm_field_data where object_id = 260;
select * from generic_ai_prompts where subject_id = 315;
select * from teams; # 36, 21, 121, [EMAIL]
SELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';
# [PASSWORD_DOTS]
select * from teams where id = 1;
select * from crm_configurations where id = 39;
select * from users where team_id = 1;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 1;
# 1 - 00541000004281rAAA
# 204 - 0052g000003freeAAA
# 429 - 0052g000003qGOiAAM
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
select * from activities where type = 'softphone'
and created_at > '2024-12-11 15:24:36' order by id desc;
select * from activity_providers where team_id = 1;
select * from activity_provider_users where activity_provider_id = 328;
select * from opportunities where crm_configuration_id = 39
AND account_id = 178 AND is_closed = false
order by created_at DESC;
select * from contacts where id = 3952;
select * from accounts where id = 178;
# [PASSWORD_DOTS]
select * from teams where id = 36;
select * from crm_configurations where id = 21;
select * from users where team_id = 36;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 36;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 36
and sa.provider = 'bullhorn';
select * from social_accounts where id = 348;
UPDATE social_accounts SET
provider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',
provider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',
expires = 1733998131,
state = 'connected'
WHERE id = 348;
# [PASSWORD_DOTS]
select * from teams where id = 31;
select * from crm_configurations where id = 18;
select * from users where team_id = 31; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 31;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 31
and sa.provider = 'close';
select * from contacts where crm_configuration_id = 18;
# [PASSWORD_DOTS] NEPTUNE [PASSWORD_DOTS]
select * from teams;
select * from users where id IN (1030, 1035, 1052);
select * from crm_configurations;
select * from users where team_id = 65; # 257
select * from team_settings where team_id = 65; # 257
select * from invitations where team_id = 65; # 257
select * from users where email = '[EMAIL]'; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 65;
select * from crm_configurations where id = 53;
select * from accounts where crm_configuration_id = 53 order by id desc;
select * from leads where crm_configuration_id = 53 order by id desc;
select * from contacts where crm_configuration_id = 53 order by id desc;
select * from opportunities where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 53 order by id desc;
select * from crm_fields where crm_configuration_id = 53 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 53 order by id desc;
select * from stages where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 13;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
and sa.provider = 'integration-app';
select * from contacts where crm_configuration_id = 13;
select * from social_accounts where sociable_id = 283;
SELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';
select * from activity_providers where team_id = 65;
SELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
;
# [PASSWORD_DOTS] STAGING [PASSWORD_DOTS]
SELECT * FROM teams;
SELECT * FROM teams WHERE id = 88;
SELECT * FROM teams WHERE id = 89;
select * from team_settings where team_id = 89;
SELECT * FROM users WHERE team_id = 89;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 89;
select * from users;
SELECT * FROM social_accounts WHERE sociable_id = 1761;
SELECT * FROM crm_configurations WHERE id = 70;
select * from accounts where crm_configuration_id = 70 order by id desc;
select * from leads where crm_configuration_id = 70 order by id desc;
select * from contacts where crm_configuration_id = 70 order by id desc;
select * from opportunities where crm_configuration_id = 70 order by id desc;
select * from crm_profiles where crm_configuration_id = 70 order by id desc;
select * from crm_fields where crm_configuration_id = 70 order by id desc;
select * from crm_field_values where crm_field_id = 3536 order by id desc;
select * from crm_layouts where crm_configuration_id = 70 order by id desc;
select * from stages where crm_configuration_id = 70 order by id desc;
select * from business_processes where crm_configuration_id = 70 order by id desc;
select * from business_process_stages where business_process_id = 34;
select * from contacts where id = 10468;
select * from crm_layouts where crm_configuration_id = 70;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;
SELECT * FROM crm_fields WHERE id IN (3533,3534,3535);
select * from activities where crm_configuration_id = 70
and (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;
SELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;
SELECT * FROM activities where crm_configuration_id = 69 ;
SELECT * FROM users WHERE email LIKE '%[EMAIL]%';
SELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;
SELECT * FROM opportunities WHERE id = 385;
select * from participants p
join activities a on p.activity_id = a.id
where a.crm_configuration_id = 70
and (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);
SELECT * FROM participants WHERE id = 1013638;
select * from teams where id = 90;
select * from users where team_id = 90;
select * from social_accounts where social_accounts.sociable_id IN (1960,1760);
SELECT * FROM crm_profiles WHERE crm_configuration_id = 71;
select * from invitations where team_id = 90;
select * from crm_configurations where id = 71;
select * from accounts where crm_configuration_id = 71 order by id desc;
select * from leads where crm_configuration_id = 71 order by id desc;
select * from contacts where crm_configuration_id = 71 order by id desc;
select * from opportunities where crm_configuration_id = 71 order by id desc;
select * from crm_profiles where crm_configuration_id = 71 order by id desc;
select * from crm_fields where crm_configuration_id = 71 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 71 order by id desc;
select * from stages where crm_configuration_id = 71 order by id desc;
select * from users order by secondary_email desc;
select u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa
join users u on sa.sociable_id = u.id
where sa.provider = 'google' and u.email LIKE 'aneliya%';
select * from failed_jobs order by id desc;
select * from users where email = '[EMAIL]' or secondary_email = '[EMAIL]';
select * from teams;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 39;
SELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;
SELECT * FROM crm_configurations WHERE id = 70;
select * from teams where id = 1;
select * from groups where team_id = 1;
select * from users where team_id = 1;
select o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o
join users u on o.user_id = u.id
join groups g on u.group_id = g.id
join...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","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\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\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":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny_jupiter","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.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":"19","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"19","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"17","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 * FROM teams WHERE id = 1;\n\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;\nSELECT * FROM crm_fields WHERE id = 2234;\nSELECT * FROM crm_field_values WHERE crm_field_id = 2234;\n\nselect * from crm_profiles where user_id = 143;\n\nselect * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO\nselect * from business_processes where crm_configuration_id = 39;\n# 01941000000H669AAC, 01941000000H66JAAS\n\nselect * from record_type_field_values\n where record_type_id IN (24);\n\nselect * from crm_field_values where id IN (2730);\n\nselect * from crm_configurations where id = 39;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce'; #1035\n\n\nselect * from users where team_id = 1; # 222 group 3\nSELECT * FROM activities WHERE user_id = 222 order by id desc;\nselect * from sidekick_settings where team_id = 1;\nselect * from teams where id = 1;\nselect * from team_features where team_id = 1;\n\nselect * from activities where crm_configuration_id = 2\nand provider = 'ms-teams' and id = 608765;\n\nSELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';\n\nselect * from sidekick_settings where team_id = 2;\n\nSELECT * FROM activities WHERE id = 608660;\nselect * from activity_summary_logs where activity_id = 608660;\nselect * from ai_prompts where transcription_id = 11214;\n\n# ********************************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;\n# id: 608818, crm: 59628809737\nSELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;\n# id: 608821, crm: 59632069252\nSELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,\nplaybook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,\nscheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at\nFROM activities a\njoin calendar_events ce on a.calendar_event_id = ce.id\nWHERE a.id IN (608818, 608821);\n\nselect * from users where team_id = 1;\nselect * from team_settings where team_id = 1;\nselect * from crm_profiles where crm_configuration_id = 39 order by user_id;\n\nselect * from team_features where team_id = 1;\n\nselect * from users where team_id = 2;\n\nSELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639\n# Preslava N. Ivanova, grou id 3\n\nSELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;\n\nselect * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';\n\nselect\n a.id,\n a.type,\n a.scheduled_start_time,\n a.actual_start_time,\n a.created_at,\n a.opportunity_id,\n a.status\nFROM activities a\nWHERE opportunity_id = 344\nand status IN ('completed', 'received', 'delivered')\nand (\n (a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))\n;\n\nSELECT * FROM users WHERE id = 222;\n\nSELECT * FROM crm_profiles WHERE user_id = 222;\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;\n\nselect * from group_deal_risk_types;\n\nselect * from opportunities where team_id = 1;\n\nSELECT * FROM opportunities WHERE id = 315;\nSELECT * FROM crm_field_data WHERE object_id = 315;\nselect * from crm_field_data where object_id = 260;\n\nselect * from generic_ai_prompts where subject_id = 315;\n\nselect * from teams; # 36, 21, 121, james.graham@bullhorn.jiminny.com\nSELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';\n\n# ************************************************************************************\nselect * from teams where id = 1;\nselect * from crm_configurations where id = 39;\nselect * from users where team_id = 1;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 1;\n# 1 - 00541000004281rAAA\n# 204 - 0052g000003freeAAA\n# 429 - 0052g000003qGOiAAM\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\nselect * from activities where type = 'softphone'\nand created_at > '2024-12-11 15:24:36' order by id desc;\n\nselect * from activity_providers where team_id = 1;\nselect * from activity_provider_users where activity_provider_id = 328;\n\nselect * from opportunities where crm_configuration_id = 39\nAND account_id = 178 AND is_closed = false\norder by created_at DESC;\n\nselect * from contacts where id = 3952;\nselect * from accounts where id = 178;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations where id = 21;\nselect * from users where team_id = 36;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 36;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 36\nand sa.provider = 'bullhorn';\n\nselect * from social_accounts where id = 348;\nUPDATE social_accounts SET\nprovider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',\nprovider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',\nexpires = 1733998131,\nstate = 'connected'\nWHERE id = 348;\n\n# ************************************************************************************\nselect * from teams where id = 31;\nselect * from crm_configurations where id = 18;\n\nselect * from users where team_id = 31; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 31;\n\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 31\nand sa.provider = 'close';\n\nselect * from contacts where crm_configuration_id = 18;\n\n# ********************** NEPTUNE **************************************************************\nselect * from teams;\nselect * from users where id IN (1030, 1035, 1052);\nselect * from crm_configurations;\n\nselect * from users where team_id = 65; # 257\nselect * from team_settings where team_id = 65; # 257\nselect * from invitations where team_id = 65; # 257\nselect * from users where email = 'integration-account@jiminny.com'; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 65;\n\nselect * from crm_configurations where id = 53;\nselect * from accounts where crm_configuration_id = 53 order by id desc;\nselect * from leads where crm_configuration_id = 53 order by id desc;\nselect * from contacts where crm_configuration_id = 53 order by id desc;\nselect * from opportunities where crm_configuration_id = 53 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 53 order by id desc;\nselect * from crm_fields where crm_configuration_id = 53 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 53 order by id desc;\nselect * from stages where crm_configuration_id = 53 order by id desc;\n\n\nselect * from crm_profiles where crm_configuration_id = 13;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\nand sa.provider = 'integration-app';\n\nselect * from contacts where crm_configuration_id = 13;\n\nselect * from social_accounts where sociable_id = 283;\n\nSELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';\n\nselect * from activity_providers where team_id = 65;\nSELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\n;\n\n# ***************************** STAGING ********************************************\nSELECT * FROM teams;\nSELECT * FROM teams WHERE id = 88;\nSELECT * FROM teams WHERE id = 89;\nselect * from team_settings where team_id = 89;\nSELECT * FROM users WHERE team_id = 89;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 89;\n\nselect * from users;\nSELECT * FROM social_accounts WHERE sociable_id = 1761;\nSELECT * FROM crm_configurations WHERE id = 70;\nselect * from accounts where crm_configuration_id = 70 order by id desc;\nselect * from leads where crm_configuration_id = 70 order by id desc;\nselect * from contacts where crm_configuration_id = 70 order by id desc;\nselect * from opportunities where crm_configuration_id = 70 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 70 order by id desc;\nselect * from crm_fields where crm_configuration_id = 70 order by id desc;\nselect * from crm_field_values where crm_field_id = 3536 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 70 order by id desc;\nselect * from stages where crm_configuration_id = 70 order by id desc;\nselect * from business_processes where crm_configuration_id = 70 order by id desc;\nselect * from business_process_stages where business_process_id = 34;\n\nselect * from contacts where id = 10468;\n\nselect * from crm_layouts where crm_configuration_id = 70;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;\nSELECT * FROM crm_fields WHERE id IN (3533,3534,3535);\n\nselect * from activities where crm_configuration_id = 70\nand (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;\n\nSELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;\nSELECT * FROM activities where crm_configuration_id = 69 ;\n\nSELECT * FROM users WHERE email LIKE '%jiminny_web_sa2@jiminny.com%';\nSELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;\nSELECT * FROM opportunities WHERE id = 385;\n\nselect * from participants p\njoin activities a on p.activity_id = a.id\nwhere a.crm_configuration_id = 70\nand (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);\nSELECT * FROM participants WHERE id = 1013638;\n\nselect * from teams where id = 90;\nselect * from users where team_id = 90;\nselect * from social_accounts where social_accounts.sociable_id IN (1960,1760);\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 71;\nselect * from invitations where team_id = 90;\n\nselect * from crm_configurations where id = 71;\nselect * from accounts where crm_configuration_id = 71 order by id desc;\nselect * from leads where crm_configuration_id = 71 order by id desc;\nselect * from contacts where crm_configuration_id = 71 order by id desc;\nselect * from opportunities where crm_configuration_id = 71 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 71 order by id desc;\nselect * from crm_fields where crm_configuration_id = 71 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 71 order by id desc;\nselect * from stages where crm_configuration_id = 71 order by id desc;\n\nselect * from users order by secondary_email desc;\nselect u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa\n join users u on sa.sociable_id = u.id\nwhere sa.provider = 'google' and u.email LIKE 'aneliya%';\n\nselect * from failed_jobs order by id desc;\n\nselect * from users where email = 'ben.allwright@learningpeople.co.uk' or secondary_email = 'ben.allwright@learningpeople.co.uk';\n\nselect * from teams;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 39;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\n# ************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;\nSELECT * FROM crm_configurations WHERE id = 70;\n\nselect * from teams where id = 1;\nselect * from groups where team_id = 1;\nselect * from users where team_id = 1;\n\nselect o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o\njoin users u on o.user_id = u.id\njoin groups g on u.group_id = g.id\njoin role_user ru on u.id = ru.user_id\njoin roles r on ru.role_id = r.id\nwhere o.crm_configuration_id = 39 and close_date > '2024-01-01 00:00:00';\n\nselect * from role_user where user_id = 143;\nselect * from roles;\n\nselect * from role_user;\nselect * from groups where id = 9;\nselect * from scope_groups where group_id = 9;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations;\nSELECT * FROM social_accounts WHERE sociable_id = 121;\n\nhttps://crmsandbox.zoho.com/crm/jiminnyw4/tab/Leads/4776201000005049105\nhttps://crmsandbox.zoho.com/crm/\n\nhttps://crm.zoho.com/crm/org3469620/tab/Leads/230045000229559080\n https://crm.zoho.com/crm/\n org3469620\n\nSELECT * FROM activities WHERE uuid_to_bin('03382d20-c8bc-48e7-a3d4-90b52fa5ceab') = uuid;\n\nselect * from users where email LIKE \"%mobile_automation_%\";\nselect * from social_accounts where sociable_id IN (2228);\nselect * from crm_profiles where user_id IN (2222,2223,2226,2227);\n\nselect * from teams order by id desc;\nSELECT * FROM users WHERE id = 2229;\nSELECT * FROM crm_profiles WHERE user_id = 2229;\nselect * from opportunities where crm_configuration_id = 88;\nselect * from crm_fields where crm_configuration_id = 88;\nselect * from crm_profiles where crm_configuration_id = 88;\n\nSELECT * FROM teams WHERE id = 1;\n\nSELECT * FROM users WHERE id = 143;\nSELECT * FROM users WHERE uuid_to_bin('fde193d3-06a2-4e1a-8895-62b94039215d') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73385071-a756-42ae-9c73-8b53f2309467') = uuid;\n\nhttps://app.staging.jiminny.com/ondemand?\n min_duration=1\n &\n only_recorded=1\n &\n user_id%5B%5D=641f1acb-16b8-42d1-8726-df52979dad0e\n &\n sequence_number=2\n\n select * from users where team_id = 1 and email like '%stoyan%'\n\nselect * from coaching_feedbacks;\n\nselect * from teams;\nSELECT * FROM users WHERE team_id = 36;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from users where id = 143;\n\nSELECT * FROM users WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM activity_shares WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\n\nselect * from users where team_id = 2;\nselect * from activities where crm_configuration_id = 39\nand activities.scheduled_start_time BETWEEN '2025-04-09 00:00:00' AND '2025-04-09 23:59:59'\nAND user_id = 143\norder by id desc;\n\n# ************************************************************************************\nselect * from teams where id = 142; # 2312, 126\nselect * from team_settings;\nselect * from users where team_id = 142; # 21642\nSELECT * FROM social_accounts WHERE sociable_id = 21642;\nSELECT * FROM crm_profiles cp join users u ON u.id = cp.user_id WHERE team_id = 142;\nselect * from crm_profiles where id IN (93);\nselect * from invitations;\nselect * from team_features where team_id = 1;\n\nSELECT * FROM crm_configurations WHERE id = 126;\nselect * from accounts where crm_configuration_id = 126 order by id desc;\nselect * from leads where crm_configuration_id = 126 order by id desc;\nselect * from contacts where crm_configuration_id = 126 order by id desc;\nselect * from opportunities where crm_configuration_id = 126 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 126 order by id desc;\nselect * from crm_fields where crm_configuration_id = 126 # 11060\n# and type IN ('picklist', 'status')\n# and object_type = 'task'\norder by id desc;\n# 5731,5732,5733\nselect DISTINCT crm_field_id from crm_field_values where crm_field_id IN (11151,12239,12215,12185,12175,12165,12144,12137,12127,12109,12107,12105,12103,12092,12037,12005,12003,11987,11969,11958,11951,11942,11931,11924,11921,11917,11915,11901,11893,11883,11872,11870,11868,11866,11839,11833,11821,11793,11780,11777,11769,11757,11737,11735,11656,11645,11638,11629,11618,11611,11602,11591,11584,11581,11558,11544,11543,11534,11532,11529,11527,11503,11497,11493,11488,11470,11468,11457,11455,11397,11387,11372,11363,11348,11323,11318,11309,11301,11300,11292,11290,11286,11284,11256,11252,11242,11237,11233,11219,11176,11160) order by id desc;\nselect * from crm_layouts where crm_configuration_id = 126 order by id desc;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id in (300,299,298);\nselect * from stages where crm_configuration_id = 126 order by id desc;\nselect * from business_processes where crm_configuration_id = 126 order by id desc;\nselect * from business_process_stages where business_process_id IN (76,75,74,73);\nselect * from playbooks where team_id = 142;\nselect * from playbook_layouts where playbook_id IN (108);\nSELECT * FROM playbook_categories WHERE playbook_id IN (108);\n\nselect * from teams where id = 130;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 2\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities\n WHERE crm_configuration_id = 110;\n\nselect * from teams;\nselect * from crm_configurations;\n\nSELECT * FROM activities WHERE id = 628773;\nSELECT * FROM crm_profiles WHERE user_id = 1460;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from teams;\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from teams where id = 145;\nselect * from crm_configurations where id = 129;\nselect * from social_accounts where sociable_id = 2317;\nSELECT * FROM activities WHERE uuid_to_bin('8dbab184-a333-4268-ad57-fb41f8d53a9a') = uuid;\n\nselect * from teams where id = 1;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 280;\nSELECT * FROM crm_layout_entities WHERE id = 5507;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type IN ('event');\n\nselect * from teams;\nselect * from activities where crm_configuration_id = 14;\n\nSELECT * FROM social_accounts where provider = 'copper';\n\nselect * from activities where id = 628467;\nselect * from participants where activity_id = 628467;\n\nSELECT * FROM contacts WHERE id = 3969;\nSELECT * FROM accounts WHERE id = 177;\n\nSELECT * FROM activities WHERE uuid_to_bin('4eb54c77-cfa3-2bd4-84a7-9ed46a21c988') = uuid;\n\n# ********************* BH\nselect * from teams where id = 36;\nSELECT * FROM crm_configurations WHERE id = 21;\nselect * from activities where crm_configuration_id = 21 and id = 607901;\nselect * from activities where crm_configuration_id = 21;\n\nselect * roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 226;\n\nselect * from migrations order by id desc;\n\n# mercury\n# neptune\n# earth\n\nselect * from teams;\nselect * from teams where id = 19;\nselect * from teams where id = 27;\nselect * from users where team_id = 27;\nSELECT * FROM crm_configurations WHERE id = 42;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from activities where id = 631461;\nSELECT * FROM crm_field_values WHERE crm_field_id = 180;\n\nselect * from teams where id = 2;\nSELECT * FROM social_accounts WHERE sociable_id = 89;\n\nSELECT * FROM activities WHERE uuid_to_bin('ba0c029a-bc14-4e17-8603-64174acebcbb') = uuid; # 634273\nselect * from activity_summary_logs where activity_id = 634273;\n\nselect * from sidekick_settings where team_id = 2;\n\nselect * from teams; # 2, 2\nSELECT * FROM crm_configurations WHERE team_id = 2; # 2\nselect * from team_features where team_id = 2;\nselect * from features;\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 and crm_provider_id = '51317301383';\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 order by id desc;\n\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from users where team_id = 1 and id IN (7160, 3248);\nselect * from migrations order by id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nselect * from teams where id = 1;\nselect * from groups g JOIN playbooks p on g.playbook_id = p.id where g.team_id = 1;\nselect * from groups where id = 565;\nselect * from playbooks where team_id = 1;\nselect * from playbooks where id = 175;\nselect * from playbook_categories where playbook_id = 175;\nselect * from users where team_id = 1052;\nselect * from users where id = 7160;\nselect * from crm_profiles where user_id = 7160;\nselect * from features;\nselect\n *\n# id, uuid, type, provider, playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id, stage_id,\n# crm_configuration_id, crm_provider_id, transcription_id, status\nfrom activities where crm_configuration_id = 1 and type = 'conference'\n# and crm_provider_id IS NOT NULL\nand provider != 'uploader' and actual_start_time IS NOT NULL\nORDER by id desc;\nselect * from activities where id = 54747783; # 00UO400000pCzojMAC\n\nselect p.id, p.activity_type, pc.id, pc.name\nFROM playbooks p\njoin playbook_categories pc on p.id = pc.playbook_id\nwhere p.team_id = 1 and p.activity_type = 'event';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 1 and object_type = 'event';\nSELECT * FROM crm_field_values WHERE crm_field_id = 4;\n\nselect * from crm_layouts cl join playbook_layouts pl on cl.id = pl.layout_id\nwhere crm_configuration_id = 1 and pl.playbook_id = 175;\n\nselect * from teams;\nSELECT r.* FROM automated_reports r\njoin teams t on r.team_id = t.id\nWHERE r.frequency = 'daily'\n and r.status = 1\nAND t.status = 'active'\nAND (r.expires_at >= now() OR r.expires_at IS NULL);\n\nselect * from automated_report_results where report_id IN (18, 33);\n\nselect * from users where team_id = 1 and id = 1047;\nSELECT * FROM social_accounts WHERE sociable_id = 1047;\n\nselect * from activity_searches where id = 10932;\nselect * from activity_search_filters where activity_search_id = 10932;\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from automated_reports where id IN (55);\nselect * from automated_report_results where id IN (81);\nselect * from users where id IN (10633, 13987, 11985);\nselect * from users where group_id IN (3710);\n\nSELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;\n\nselect * from teams;\nselect * from accounts where team_id = 1;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('82e74956-6144-4cd1-a3d3-af985c3070a4') = uuid;\n\nselect * from teams where id = 1029;\nselect * from crm_configurations where provider = 'pipedrive';\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 = 1029 and sa.provider = 'pipedrive';\n\n[\n {\n \"user_id\": \"23460 (owner)\",\n \"email\": \"integration-account@pipedrive.jiminny.com\",\n \"id\": 69,\n \"sociable_id\": 23460,\n \"provider_user_id\": \"19555731\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:rYyABXmXsBhEdYU_dfmDH8GF-vzSseJXE5bds_zAyVdAwlTXOPdTl9i4PS4jVofLvpq7IRgvEt2BzGhR6cWiQXHHD0AtayQOkZm262ClFCsMYtKGfep0Jq1n0eiRIVqT9gAY7rWvhpEDF8oAlgnRGmqx-euIkpzE79sPXh4OjNx_yUIaanjyplGpBBJ_NiACd1sMlZmseyUyyU_gldqlCBAuK9hhATc9icgg7zuoc7nKBBrlg49tRtzEagDh6xbFBpzfCp7kE_7n4TLWfWHLPMzu-bktjwA969G9sFRmoH1GjPA0a2odDT4dk1_1ouBrB1NcTT2hQUqH-_RzDW2nWmeoVHA\",\n \"provider_refresh_token\": \"5034113:19555731:87c14258f0c813d02767ee975f6044d46b6b2bfc\",\n \"expires\": 1779091997,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"connected\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 08:23:28\",\n \"updated_at\": \"2026-05-18 07:13:18\",\n \"provider_user_token_encrypted\": \"eyJpdiI6Ik9oYzBwcTVteWN4ajBRaDdMb0FjWGc9PSIsInZhbHVlIjoiQUNMbjU5UHR2Q1RnbWRXMEU1TUx6UVpRU3gzdVc5WktmTE4rVlhXa3lRaGhyUUlZMVZRWEJuR0JaWWhZZXNPRlBuanhuYU5MVHZ5TG9NTVVjNjJSUUpZZ2VhbGYxbHg0UzJEdTVmQjNFZnJRZkMwYjd0N2RMZ05GRS9IR3c2K0NoVjBjYTA5UG12SkxHeDlDMGVNN3ptUWUzblFiTngyYzR1eUpHSEYrdEwvZm0yZklGYjBSNEtTR2ZGazhLM1hqT3lVbjFobDNPZ0d3anFlcjhKcXpERlZGOVN1YmFyNDIvM1BFRDFMYnp4WEI4TGVLM2xYcy9CL0RDOWlQNHI3N0NwWnJPMWRtZllmM2ZKeE9TV2NBeDZxL2M1YnlSVzd3ZW96T3F1QmtBYXBHYkUraGcvdCtRajlYZXBjVVBSdFlMUjVPVDVJbDdyenVoWjMrbVJvU3ZZR1dQZ3pqQ3F3aDF2U2xPZWZIN3BCWVFLNXpxQUtDb2pIK0xHc1E3SklSM3Q0VkNSbm9oK2pFK3hLaW54T1dWbEVneUp0RGhhdVBuOFI4MXROc3dZWnFnTUpiaDVMMnZ4QmlRM3k4QWFlMVFWUFYvdGhJQzZBYnhBQmhWa2ZKN1ZhSnhpaExxbmlTemgzUWw3aXJtWjlSMlhmd0lWMDNDN1N3My9Ua0hCL2xqY3RkVFhMSjFJMDRjOE5DWlgrZ3FMVXN6RWlwUE5GWERZdG1xVjVxOFlLRGs2VVJKS3FLeWRxQjYxdDh4Z2JJNXhlWEZ3dkQ4SGtybDNUcndzblFHeVJNRkYraFh2UDFIUTdMQ1BZa3dEU1dBbzk5K0dyT2RNVFBZZUJpRytSck5pYlI1YUZyMmhUNEZCdWxHYmJLREtzbUpjVkhvV0RoejJpbm1SWHlNaXE5M0RhcS94UW9EdFoweWF3bVFVY0dTZWFPSXBmOCtDYndia215cmtyZU1oT0Exam1CV2tPblNhYjY4clVEeUs3anVHUmNHeS9YLzRha1VhbGl3N3lwaDlzZnRhQUZta2s4eFllNHgzRklSRmNyazJ4dlBDMnByNCtBRjNaVjJCTT0iLCJtYWMiOiJkYTQxZDY1OTY2ZTljMTgyZWRhNGEzMGZjZDc2MjBjN2NlNzU2YTViNGQxNWE1NTI2ZmI1MWQyYjQ2ODYxZmEwIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6Imt2bGxlSmxUK05GMjF0dEtPaTMrUlE9PSIsInZhbHVlIjoiUXZHTElZRXkreHFxUU02SnZ4eVBacG9WWTRlVkd0USszV3JyVFlpU2ZaY25GSWo2WFcrRzNlbFRlUXRQczNwSXRCcEdvZEpveG9jMzBDSTgwdnZLQnc9PSIsIm1hYyI6ImQxYWI0NzU5Nzg5MDI4YWVhZmQ4Mjg1YzhkZDQzMjRkYWYwYTdhZTY5MDMxMjc0OWNiYjY0Nzc3NDQ0MTEyY2EiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300786192D9D96DD60D3D1EBC9DFAEE5F0C45EE80165CF3F3D2B3B627026AA7CFC7CA0128DD463535D32EE491ADBADF8B07596B0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040C7FB1319048ECB2EA3F23B995020110802B52D22F5EAD341AB238FBBCB6093156E443876A664BA5555D722565C2B2D04422C868CD7350555E3CC74221\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n },\n {\n \"user_id\": \"23463\",\n \"email\": \"jiminny_web_sa@pipedrive.jiminny.com\",\n \"id\": 72,\n \"sociable_id\": 23463,\n \"provider_user_id\": \"23270841\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:txqCuWLeVhgwiaFqXIvQWWrtrnFIy_4lT3VCr-sRB4g6_2lK8KcQ_6ka_qFmZhr-IeIAKmAImx6H1iIKx4Ab7XZ5MnKIh03GKbHjI0n0rGT9UYkeH21jKOxJvKaSX_TyLbxFPR6irPQyvqcpBClXI52gVJH01KzZy_dMTHFXhhDLOIhEpSrQXHG7Qo8q7OuBeSPZrU1ALi9kmAm4GTpzGTbzfl-hUt9IAfPunJOCyv3mf2Tl-MT8EyQgOFPrsP3yz9UlSyVhb40zO_bCnUrqNxjwgm_E6vgpVrwULTQbHe-43Dq-TRetjceUzT88GBgVJ0UdxXP5BRBVXcL5ir8-9ZTMaNU\",\n \"provider_refresh_token\": \"5034113:23270841:34790b44838f5fd422c2d2c82e00f1ecf2178ad1\",\n \"expires\": 1753837219,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"full-refresh\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 10:41:12\",\n \"updated_at\": \"2025-07-30 01:00:17\",\n \"provider_user_token_encrypted\": \"eyJpdiI6InVEVEl2SzIxMjd1bkNDWG9lY3YvQ0E9PSIsInZhbHVlIjoiRlJLbDZ3ZHo2dHMxUWQwdGU2YUZjV3lPWHlxQTJ0eWh4S0RTMjlSaThVcktoaWhXcTd2UXl4Mjg4bW5UUnZCZEQ5NXpuQTVKOURiMDNIa3l3K0lSWCt5azRBOEdHbitWQXhxeEpMVUZ1dnF2NVl1TTZLelZOaGNvRlBLeGpIWlpoRGloUEprd2xoNUFPcTlLcUd3WVlUU2svR1NOeXBYQ2NnMWhnK1V2aytOeVVMNzJGdVZXMU1JS3BSaGNCcmxkVjEwQ01mQXNBdWNhS1lMZWZobnZwcHBkN1R4bUVDRUNYdnNtSVJkdG5MdkN3djJBT0hMRDl1MHFGbnl4WU13ejBkUWsrdUljWkZhcTJlN0JDSGdTVzlPY0FGMUJlZi9WRGpkMUk5R20wblYwSk9VR2FuaHpLTzJNeitMbnF1V1NEMUUxRmYzaDRGZDMyaXd3Z0FjQno4SzVoYjUyTmV3UXNpRlF4TGZKNVl3dUFqdGhKVWJjRVlUUXRGalBpaXJvSGJmbS8rd25aQ2Zvc05saHRDRjlHV1VEUFFiRU5xbWRVNkxFSXV0RUZyaUlYNWMwMmhnZ0Y1VUQ4eEFkY2QyWXpnR0NidkVJSWdjVGljUjA3NDdpZW9WUHhtSlpGSGdNU2hRUTA5ZW03RGpiRFdrdytkOHJXSUxlazZNaG9iaUg2NFZYdEc3YklMeFZvblBzWmVRSDcvN2M4WUNtL3h4S2IrUW00cXhialBia3BJcW5XallBNlV5WWdhcE1ZVFBBM3RSSUVBamYvOGZEQWM5a2FJMGwyWkRSU3dlTEtPemZlQ3RXRGNDcEdYRHdMNTlTQVg2SUdUN0hVaXdZT1dUOUlrVzkrZHFBemhwWXg1cm4rSy9UOHUzcnNSM2dISlhBRTEyVUNyTkZYaFJYUlN1a2RKVHhhM2dHckR3a1JGaVZ2Wk9BVnhTclVpSEhwWTVpQTlJbXVkOUxSTGpRbDk0a1VtbE9QMVAvN3VlVEhJUHd2elowd0laNVIzZ3M3N0ZOK0NDakIwQ2FicGxoMDBhTXI0VUppUmFOZHdlWUdGV21NNFQ4RU1nY0dnWT0iLCJtYWMiOiI0ZTU4ZmJkNTdkYmY0NGE4NTJjZjlhNDExNzE2YjhlOWM2NTA5OGY2MDA4OTcyZDVlOTljY2JjZDhmMjBhMDUyIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6IkJGMkdRVHRKM2VTcitKNGcvQWJtUGc9PSIsInZhbHVlIjoicmFyRkxPZ1Rybm1ORXlEVjJ2TXFGTzJtM3hWaFhnUVVHN2ZlR1lRM0I5d3ozbnZTcU5EdzJqRkI2elhyNWhlenRTUXV3bjk0N1JXeklDMVAyUzBKcHc9PSIsIm1hYyI6ImJhODVjMGQyZDE3Y2ExNjc2OWVjYWJiNmFjYWVkODIyMTMyNWVhYTExMTgwYTEyMTU0MzUzZGE1YjQ5YzQ5ZjEiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300788C37CDF66ABE9301A68D5D4866AC0C197E04EEE4D904F20A59991322EBAE252301BEF4B24FF01359E934E5654617E4EEAC0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040CEB00EF45BDEA999A5558889E020110802B925F372F7BEFAF0B45E48686113D1DA430ECFCC07B1F61BA6828CC44235278EDB05C486E8068D0BE737D91\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n }\n]","depth":4,"on_screen":true,"value":"SELECT * FROM teams WHERE id = 1;\n\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;\nSELECT * FROM crm_fields WHERE id = 2234;\nSELECT * FROM crm_field_values WHERE crm_field_id = 2234;\n\nselect * from crm_profiles where user_id = 143;\n\nselect * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO\nselect * from business_processes where crm_configuration_id = 39;\n# 01941000000H669AAC, 01941000000H66JAAS\n\nselect * from record_type_field_values\n where record_type_id IN (24);\n\nselect * from crm_field_values where id IN (2730);\n\nselect * from crm_configurations where id = 39;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce'; #1035\n\n\nselect * from users where team_id = 1; # 222 group 3\nSELECT * FROM activities WHERE user_id = 222 order by id desc;\nselect * from sidekick_settings where team_id = 1;\nselect * from teams where id = 1;\nselect * from team_features where team_id = 1;\n\nselect * from activities where crm_configuration_id = 2\nand provider = 'ms-teams' and id = 608765;\n\nSELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';\n\nselect * from sidekick_settings where team_id = 2;\n\nSELECT * FROM activities WHERE id = 608660;\nselect * from activity_summary_logs where activity_id = 608660;\nselect * from ai_prompts where transcription_id = 11214;\n\n# ********************************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;\n# id: 608818, crm: 59628809737\nSELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;\n# id: 608821, crm: 59632069252\nSELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,\nplaybook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,\nscheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at\nFROM activities a\njoin calendar_events ce on a.calendar_event_id = ce.id\nWHERE a.id IN (608818, 608821);\n\nselect * from users where team_id = 1;\nselect * from team_settings where team_id = 1;\nselect * from crm_profiles where crm_configuration_id = 39 order by user_id;\n\nselect * from team_features where team_id = 1;\n\nselect * from users where team_id = 2;\n\nSELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639\n# Preslava N. Ivanova, grou id 3\n\nSELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;\n\nselect * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';\n\nselect\n a.id,\n a.type,\n a.scheduled_start_time,\n a.actual_start_time,\n a.created_at,\n a.opportunity_id,\n a.status\nFROM activities a\nWHERE opportunity_id = 344\nand status IN ('completed', 'received', 'delivered')\nand (\n (a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))\n;\n\nSELECT * FROM users WHERE id = 222;\n\nSELECT * FROM crm_profiles WHERE user_id = 222;\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;\n\nselect * from group_deal_risk_types;\n\nselect * from opportunities where team_id = 1;\n\nSELECT * FROM opportunities WHERE id = 315;\nSELECT * FROM crm_field_data WHERE object_id = 315;\nselect * from crm_field_data where object_id = 260;\n\nselect * from generic_ai_prompts where subject_id = 315;\n\nselect * from teams; # 36, 21, 121, james.graham@bullhorn.jiminny.com\nSELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';\n\n# ************************************************************************************\nselect * from teams where id = 1;\nselect * from crm_configurations where id = 39;\nselect * from users where team_id = 1;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 1;\n# 1 - 00541000004281rAAA\n# 204 - 0052g000003freeAAA\n# 429 - 0052g000003qGOiAAM\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\nselect * from activities where type = 'softphone'\nand created_at > '2024-12-11 15:24:36' order by id desc;\n\nselect * from activity_providers where team_id = 1;\nselect * from activity_provider_users where activity_provider_id = 328;\n\nselect * from opportunities where crm_configuration_id = 39\nAND account_id = 178 AND is_closed = false\norder by created_at DESC;\n\nselect * from contacts where id = 3952;\nselect * from accounts where id = 178;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations where id = 21;\nselect * from users where team_id = 36;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 36;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 36\nand sa.provider = 'bullhorn';\n\nselect * from social_accounts where id = 348;\nUPDATE social_accounts SET\nprovider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',\nprovider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',\nexpires = 1733998131,\nstate = 'connected'\nWHERE id = 348;\n\n# ************************************************************************************\nselect * from teams where id = 31;\nselect * from crm_configurations where id = 18;\n\nselect * from users where team_id = 31; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 31;\n\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 31\nand sa.provider = 'close';\n\nselect * from contacts where crm_configuration_id = 18;\n\n# ********************** NEPTUNE **************************************************************\nselect * from teams;\nselect * from users where id IN (1030, 1035, 1052);\nselect * from crm_configurations;\n\nselect * from users where team_id = 65; # 257\nselect * from team_settings where team_id = 65; # 257\nselect * from invitations where team_id = 65; # 257\nselect * from users where email = 'integration-account@jiminny.com'; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 65;\n\nselect * from crm_configurations where id = 53;\nselect * from accounts where crm_configuration_id = 53 order by id desc;\nselect * from leads where crm_configuration_id = 53 order by id desc;\nselect * from contacts where crm_configuration_id = 53 order by id desc;\nselect * from opportunities where crm_configuration_id = 53 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 53 order by id desc;\nselect * from crm_fields where crm_configuration_id = 53 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 53 order by id desc;\nselect * from stages where crm_configuration_id = 53 order by id desc;\n\n\nselect * from crm_profiles where crm_configuration_id = 13;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\nand sa.provider = 'integration-app';\n\nselect * from contacts where crm_configuration_id = 13;\n\nselect * from social_accounts where sociable_id = 283;\n\nSELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';\n\nselect * from activity_providers where team_id = 65;\nSELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\n;\n\n# ***************************** STAGING ********************************************\nSELECT * FROM teams;\nSELECT * FROM teams WHERE id = 88;\nSELECT * FROM teams WHERE id = 89;\nselect * from team_settings where team_id = 89;\nSELECT * FROM users WHERE team_id = 89;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 89;\n\nselect * from users;\nSELECT * FROM social_accounts WHERE sociable_id = 1761;\nSELECT * FROM crm_configurations WHERE id = 70;\nselect * from accounts where crm_configuration_id = 70 order by id desc;\nselect * from leads where crm_configuration_id = 70 order by id desc;\nselect * from contacts where crm_configuration_id = 70 order by id desc;\nselect * from opportunities where crm_configuration_id = 70 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 70 order by id desc;\nselect * from crm_fields where crm_configuration_id = 70 order by id desc;\nselect * from crm_field_values where crm_field_id = 3536 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 70 order by id desc;\nselect * from stages where crm_configuration_id = 70 order by id desc;\nselect * from business_processes where crm_configuration_id = 70 order by id desc;\nselect * from business_process_stages where business_process_id = 34;\n\nselect * from contacts where id = 10468;\n\nselect * from crm_layouts where crm_configuration_id = 70;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;\nSELECT * FROM crm_fields WHERE id IN (3533,3534,3535);\n\nselect * from activities where crm_configuration_id = 70\nand (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;\n\nSELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;\nSELECT * FROM activities where crm_configuration_id = 69 ;\n\nSELECT * FROM users WHERE email LIKE '%jiminny_web_sa2@jiminny.com%';\nSELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;\nSELECT * FROM opportunities WHERE id = 385;\n\nselect * from participants p\njoin activities a on p.activity_id = a.id\nwhere a.crm_configuration_id = 70\nand (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);\nSELECT * FROM participants WHERE id = 1013638;\n\nselect * from teams where id = 90;\nselect * from users where team_id = 90;\nselect * from social_accounts where social_accounts.sociable_id IN (1960,1760);\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 71;\nselect * from invitations where team_id = 90;\n\nselect * from crm_configurations where id = 71;\nselect * from accounts where crm_configuration_id = 71 order by id desc;\nselect * from leads where crm_configuration_id = 71 order by id desc;\nselect * from contacts where crm_configuration_id = 71 order by id desc;\nselect * from opportunities where crm_configuration_id = 71 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 71 order by id desc;\nselect * from crm_fields where crm_configuration_id = 71 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 71 order by id desc;\nselect * from stages where crm_configuration_id = 71 order by id desc;\n\nselect * from users order by secondary_email desc;\nselect u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa\n join users u on sa.sociable_id = u.id\nwhere sa.provider = 'google' and u.email LIKE 'aneliya%';\n\nselect * from failed_jobs order by id desc;\n\nselect * from users where email = 'ben.allwright@learningpeople.co.uk' or secondary_email = 'ben.allwright@learningpeople.co.uk';\n\nselect * from teams;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 39;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\n# ************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;\nSELECT * FROM crm_configurations WHERE id = 70;\n\nselect * from teams where id = 1;\nselect * from groups where team_id = 1;\nselect * from users where team_id = 1;\n\nselect o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o\njoin users u on o.user_id = u.id\njoin groups g on u.group_id = g.id\njoin role_user ru on u.id = ru.user_id\njoin roles r on ru.role_id = r.id\nwhere o.crm_configuration_id = 39 and close_date > '2024-01-01 00:00:00';\n\nselect * from role_user where user_id = 143;\nselect * from roles;\n\nselect * from role_user;\nselect * from groups where id = 9;\nselect * from scope_groups where group_id = 9;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations;\nSELECT * FROM social_accounts WHERE sociable_id = 121;\n\nhttps://crmsandbox.zoho.com/crm/jiminnyw4/tab/Leads/4776201000005049105\nhttps://crmsandbox.zoho.com/crm/\n\nhttps://crm.zoho.com/crm/org3469620/tab/Leads/230045000229559080\n https://crm.zoho.com/crm/\n org3469620\n\nSELECT * FROM activities WHERE uuid_to_bin('03382d20-c8bc-48e7-a3d4-90b52fa5ceab') = uuid;\n\nselect * from users where email LIKE \"%mobile_automation_%\";\nselect * from social_accounts where sociable_id IN (2228);\nselect * from crm_profiles where user_id IN (2222,2223,2226,2227);\n\nselect * from teams order by id desc;\nSELECT * FROM users WHERE id = 2229;\nSELECT * FROM crm_profiles WHERE user_id = 2229;\nselect * from opportunities where crm_configuration_id = 88;\nselect * from crm_fields where crm_configuration_id = 88;\nselect * from crm_profiles where crm_configuration_id = 88;\n\nSELECT * FROM teams WHERE id = 1;\n\nSELECT * FROM users WHERE id = 143;\nSELECT * FROM users WHERE uuid_to_bin('fde193d3-06a2-4e1a-8895-62b94039215d') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73385071-a756-42ae-9c73-8b53f2309467') = uuid;\n\nhttps://app.staging.jiminny.com/ondemand?\n min_duration=1\n &\n only_recorded=1\n &\n user_id%5B%5D=641f1acb-16b8-42d1-8726-df52979dad0e\n &\n sequence_number=2\n\n select * from users where team_id = 1 and email like '%stoyan%'\n\nselect * from coaching_feedbacks;\n\nselect * from teams;\nSELECT * FROM users WHERE team_id = 36;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from users where id = 143;\n\nSELECT * FROM users WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM activity_shares WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\n\nselect * from users where team_id = 2;\nselect * from activities where crm_configuration_id = 39\nand activities.scheduled_start_time BETWEEN '2025-04-09 00:00:00' AND '2025-04-09 23:59:59'\nAND user_id = 143\norder by id desc;\n\n# ************************************************************************************\nselect * from teams where id = 142; # 2312, 126\nselect * from team_settings;\nselect * from users where team_id = 142; # 21642\nSELECT * FROM social_accounts WHERE sociable_id = 21642;\nSELECT * FROM crm_profiles cp join users u ON u.id = cp.user_id WHERE team_id = 142;\nselect * from crm_profiles where id IN (93);\nselect * from invitations;\nselect * from team_features where team_id = 1;\n\nSELECT * FROM crm_configurations WHERE id = 126;\nselect * from accounts where crm_configuration_id = 126 order by id desc;\nselect * from leads where crm_configuration_id = 126 order by id desc;\nselect * from contacts where crm_configuration_id = 126 order by id desc;\nselect * from opportunities where crm_configuration_id = 126 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 126 order by id desc;\nselect * from crm_fields where crm_configuration_id = 126 # 11060\n# and type IN ('picklist', 'status')\n# and object_type = 'task'\norder by id desc;\n# 5731,5732,5733\nselect DISTINCT crm_field_id from crm_field_values where crm_field_id IN (11151,12239,12215,12185,12175,12165,12144,12137,12127,12109,12107,12105,12103,12092,12037,12005,12003,11987,11969,11958,11951,11942,11931,11924,11921,11917,11915,11901,11893,11883,11872,11870,11868,11866,11839,11833,11821,11793,11780,11777,11769,11757,11737,11735,11656,11645,11638,11629,11618,11611,11602,11591,11584,11581,11558,11544,11543,11534,11532,11529,11527,11503,11497,11493,11488,11470,11468,11457,11455,11397,11387,11372,11363,11348,11323,11318,11309,11301,11300,11292,11290,11286,11284,11256,11252,11242,11237,11233,11219,11176,11160) order by id desc;\nselect * from crm_layouts where crm_configuration_id = 126 order by id desc;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id in (300,299,298);\nselect * from stages where crm_configuration_id = 126 order by id desc;\nselect * from business_processes where crm_configuration_id = 126 order by id desc;\nselect * from business_process_stages where business_process_id IN (76,75,74,73);\nselect * from playbooks where team_id = 142;\nselect * from playbook_layouts where playbook_id IN (108);\nSELECT * FROM playbook_categories WHERE playbook_id IN (108);\n\nselect * from teams where id = 130;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 2\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities\n WHERE crm_configuration_id = 110;\n\nselect * from teams;\nselect * from crm_configurations;\n\nSELECT * FROM activities WHERE id = 628773;\nSELECT * FROM crm_profiles WHERE user_id = 1460;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from teams;\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from teams where id = 145;\nselect * from crm_configurations where id = 129;\nselect * from social_accounts where sociable_id = 2317;\nSELECT * FROM activities WHERE uuid_to_bin('8dbab184-a333-4268-ad57-fb41f8d53a9a') = uuid;\n\nselect * from teams where id = 1;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 280;\nSELECT * FROM crm_layout_entities WHERE id = 5507;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type IN ('event');\n\nselect * from teams;\nselect * from activities where crm_configuration_id = 14;\n\nSELECT * FROM social_accounts where provider = 'copper';\n\nselect * from activities where id = 628467;\nselect * from participants where activity_id = 628467;\n\nSELECT * FROM contacts WHERE id = 3969;\nSELECT * FROM accounts WHERE id = 177;\n\nSELECT * FROM activities WHERE uuid_to_bin('4eb54c77-cfa3-2bd4-84a7-9ed46a21c988') = uuid;\n\n# ********************* BH\nselect * from teams where id = 36;\nSELECT * FROM crm_configurations WHERE id = 21;\nselect * from activities where crm_configuration_id = 21 and id = 607901;\nselect * from activities where crm_configuration_id = 21;\n\nselect * roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 226;\n\nselect * from migrations order by id desc;\n\n# mercury\n# neptune\n# earth\n\nselect * from teams;\nselect * from teams where id = 19;\nselect * from teams where id = 27;\nselect * from users where team_id = 27;\nSELECT * FROM crm_configurations WHERE id = 42;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from activities where id = 631461;\nSELECT * FROM crm_field_values WHERE crm_field_id = 180;\n\nselect * from teams where id = 2;\nSELECT * FROM social_accounts WHERE sociable_id = 89;\n\nSELECT * FROM activities WHERE uuid_to_bin('ba0c029a-bc14-4e17-8603-64174acebcbb') = uuid; # 634273\nselect * from activity_summary_logs where activity_id = 634273;\n\nselect * from sidekick_settings where team_id = 2;\n\nselect * from teams; # 2, 2\nSELECT * FROM crm_configurations WHERE team_id = 2; # 2\nselect * from team_features where team_id = 2;\nselect * from features;\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 and crm_provider_id = '51317301383';\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 order by id desc;\n\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from users where team_id = 1 and id IN (7160, 3248);\nselect * from migrations order by id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nselect * from teams where id = 1;\nselect * from groups g JOIN playbooks p on g.playbook_id = p.id where g.team_id = 1;\nselect * from groups where id = 565;\nselect * from playbooks where team_id = 1;\nselect * from playbooks where id = 175;\nselect * from playbook_categories where playbook_id = 175;\nselect * from users where team_id = 1052;\nselect * from users where id = 7160;\nselect * from crm_profiles where user_id = 7160;\nselect * from features;\nselect\n *\n# id, uuid, type, provider, playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id, stage_id,\n# crm_configuration_id, crm_provider_id, transcription_id, status\nfrom activities where crm_configuration_id = 1 and type = 'conference'\n# and crm_provider_id IS NOT NULL\nand provider != 'uploader' and actual_start_time IS NOT NULL\nORDER by id desc;\nselect * from activities where id = 54747783; # 00UO400000pCzojMAC\n\nselect p.id, p.activity_type, pc.id, pc.name\nFROM playbooks p\njoin playbook_categories pc on p.id = pc.playbook_id\nwhere p.team_id = 1 and p.activity_type = 'event';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 1 and object_type = 'event';\nSELECT * FROM crm_field_values WHERE crm_field_id = 4;\n\nselect * from crm_layouts cl join playbook_layouts pl on cl.id = pl.layout_id\nwhere crm_configuration_id = 1 and pl.playbook_id = 175;\n\nselect * from teams;\nSELECT r.* FROM automated_reports r\njoin teams t on r.team_id = t.id\nWHERE r.frequency = 'daily'\n and r.status = 1\nAND t.status = 'active'\nAND (r.expires_at >= now() OR r.expires_at IS NULL);\n\nselect * from automated_report_results where report_id IN (18, 33);\n\nselect * from users where team_id = 1 and id = 1047;\nSELECT * FROM social_accounts WHERE sociable_id = 1047;\n\nselect * from activity_searches where id = 10932;\nselect * from activity_search_filters where activity_search_id = 10932;\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from automated_reports where id IN (55);\nselect * from automated_report_results where id IN (81);\nselect * from users where id IN (10633, 13987, 11985);\nselect * from users where group_id IN (3710);\n\nSELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;\n\nselect * from teams;\nselect * from accounts where team_id = 1;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('82e74956-6144-4cd1-a3d3-af985c3070a4') = uuid;\n\nselect * from teams where id = 1029;\nselect * from crm_configurations where provider = 'pipedrive';\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 = 1029 and sa.provider = 'pipedrive';\n\n[\n {\n \"user_id\": \"23460 (owner)\",\n \"email\": \"integration-account@pipedrive.jiminny.com\",\n \"id\": 69,\n \"sociable_id\": 23460,\n \"provider_user_id\": \"19555731\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:rYyABXmXsBhEdYU_dfmDH8GF-vzSseJXE5bds_zAyVdAwlTXOPdTl9i4PS4jVofLvpq7IRgvEt2BzGhR6cWiQXHHD0AtayQOkZm262ClFCsMYtKGfep0Jq1n0eiRIVqT9gAY7rWvhpEDF8oAlgnRGmqx-euIkpzE79sPXh4OjNx_yUIaanjyplGpBBJ_NiACd1sMlZmseyUyyU_gldqlCBAuK9hhATc9icgg7zuoc7nKBBrlg49tRtzEagDh6xbFBpzfCp7kE_7n4TLWfWHLPMzu-bktjwA969G9sFRmoH1GjPA0a2odDT4dk1_1ouBrB1NcTT2hQUqH-_RzDW2nWmeoVHA\",\n \"provider_refresh_token\": \"5034113:19555731:87c14258f0c813d02767ee975f6044d46b6b2bfc\",\n \"expires\": 1779091997,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"connected\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 08:23:28\",\n \"updated_at\": \"2026-05-18 07:13:18\",\n \"provider_user_token_encrypted\": \"eyJpdiI6Ik9oYzBwcTVteWN4ajBRaDdMb0FjWGc9PSIsInZhbHVlIjoiQUNMbjU5UHR2Q1RnbWRXMEU1TUx6UVpRU3gzdVc5WktmTE4rVlhXa3lRaGhyUUlZMVZRWEJuR0JaWWhZZXNPRlBuanhuYU5MVHZ5TG9NTVVjNjJSUUpZZ2VhbGYxbHg0UzJEdTVmQjNFZnJRZkMwYjd0N2RMZ05GRS9IR3c2K0NoVjBjYTA5UG12SkxHeDlDMGVNN3ptUWUzblFiTngyYzR1eUpHSEYrdEwvZm0yZklGYjBSNEtTR2ZGazhLM1hqT3lVbjFobDNPZ0d3anFlcjhKcXpERlZGOVN1YmFyNDIvM1BFRDFMYnp4WEI4TGVLM2xYcy9CL0RDOWlQNHI3N0NwWnJPMWRtZllmM2ZKeE9TV2NBeDZxL2M1YnlSVzd3ZW96T3F1QmtBYXBHYkUraGcvdCtRajlYZXBjVVBSdFlMUjVPVDVJbDdyenVoWjMrbVJvU3ZZR1dQZ3pqQ3F3aDF2U2xPZWZIN3BCWVFLNXpxQUtDb2pIK0xHc1E3SklSM3Q0VkNSbm9oK2pFK3hLaW54T1dWbEVneUp0RGhhdVBuOFI4MXROc3dZWnFnTUpiaDVMMnZ4QmlRM3k4QWFlMVFWUFYvdGhJQzZBYnhBQmhWa2ZKN1ZhSnhpaExxbmlTemgzUWw3aXJtWjlSMlhmd0lWMDNDN1N3My9Ua0hCL2xqY3RkVFhMSjFJMDRjOE5DWlgrZ3FMVXN6RWlwUE5GWERZdG1xVjVxOFlLRGs2VVJKS3FLeWRxQjYxdDh4Z2JJNXhlWEZ3dkQ4SGtybDNUcndzblFHeVJNRkYraFh2UDFIUTdMQ1BZa3dEU1dBbzk5K0dyT2RNVFBZZUJpRytSck5pYlI1YUZyMmhUNEZCdWxHYmJLREtzbUpjVkhvV0RoejJpbm1SWHlNaXE5M0RhcS94UW9EdFoweWF3bVFVY0dTZWFPSXBmOCtDYndia215cmtyZU1oT0Exam1CV2tPblNhYjY4clVEeUs3anVHUmNHeS9YLzRha1VhbGl3N3lwaDlzZnRhQUZta2s4eFllNHgzRklSRmNyazJ4dlBDMnByNCtBRjNaVjJCTT0iLCJtYWMiOiJkYTQxZDY1OTY2ZTljMTgyZWRhNGEzMGZjZDc2MjBjN2NlNzU2YTViNGQxNWE1NTI2ZmI1MWQyYjQ2ODYxZmEwIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6Imt2bGxlSmxUK05GMjF0dEtPaTMrUlE9PSIsInZhbHVlIjoiUXZHTElZRXkreHFxUU02SnZ4eVBacG9WWTRlVkd0USszV3JyVFlpU2ZaY25GSWo2WFcrRzNlbFRlUXRQczNwSXRCcEdvZEpveG9jMzBDSTgwdnZLQnc9PSIsIm1hYyI6ImQxYWI0NzU5Nzg5MDI4YWVhZmQ4Mjg1YzhkZDQzMjRkYWYwYTdhZTY5MDMxMjc0OWNiYjY0Nzc3NDQ0MTEyY2EiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300786192D9D96DD60D3D1EBC9DFAEE5F0C45EE80165CF3F3D2B3B627026AA7CFC7CA0128DD463535D32EE491ADBADF8B07596B0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040C7FB1319048ECB2EA3F23B995020110802B52D22F5EAD341AB238FBBCB6093156E443876A664BA5555D722565C2B2D04422C868CD7350555E3CC74221\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n },\n {\n \"user_id\": \"23463\",\n \"email\": \"jiminny_web_sa@pipedrive.jiminny.com\",\n \"id\": 72,\n \"sociable_id\": 23463,\n \"provider_user_id\": \"23270841\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:txqCuWLeVhgwiaFqXIvQWWrtrnFIy_4lT3VCr-sRB4g6_2lK8KcQ_6ka_qFmZhr-IeIAKmAImx6H1iIKx4Ab7XZ5MnKIh03GKbHjI0n0rGT9UYkeH21jKOxJvKaSX_TyLbxFPR6irPQyvqcpBClXI52gVJH01KzZy_dMTHFXhhDLOIhEpSrQXHG7Qo8q7OuBeSPZrU1ALi9kmAm4GTpzGTbzfl-hUt9IAfPunJOCyv3mf2Tl-MT8EyQgOFPrsP3yz9UlSyVhb40zO_bCnUrqNxjwgm_E6vgpVrwULTQbHe-43Dq-TRetjceUzT88GBgVJ0UdxXP5BRBVXcL5ir8-9ZTMaNU\",\n \"provider_refresh_token\": \"5034113:23270841:34790b44838f5fd422c2d2c82e00f1ecf2178ad1\",\n \"expires\": 1753837219,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"full-refresh\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 10:41:12\",\n \"updated_at\": \"2025-07-30 01:00:17\",\n \"provider_user_token_encrypted\": \"eyJpdiI6InVEVEl2SzIxMjd1bkNDWG9lY3YvQ0E9PSIsInZhbHVlIjoiRlJLbDZ3ZHo2dHMxUWQwdGU2YUZjV3lPWHlxQTJ0eWh4S0RTMjlSaThVcktoaWhXcTd2UXl4Mjg4bW5UUnZCZEQ5NXpuQTVKOURiMDNIa3l3K0lSWCt5azRBOEdHbitWQXhxeEpMVUZ1dnF2NVl1TTZLelZOaGNvRlBLeGpIWlpoRGloUEprd2xoNUFPcTlLcUd3WVlUU2svR1NOeXBYQ2NnMWhnK1V2aytOeVVMNzJGdVZXMU1JS3BSaGNCcmxkVjEwQ01mQXNBdWNhS1lMZWZobnZwcHBkN1R4bUVDRUNYdnNtSVJkdG5MdkN3djJBT0hMRDl1MHFGbnl4WU13ejBkUWsrdUljWkZhcTJlN0JDSGdTVzlPY0FGMUJlZi9WRGpkMUk5R20wblYwSk9VR2FuaHpLTzJNeitMbnF1V1NEMUUxRmYzaDRGZDMyaXd3Z0FjQno4SzVoYjUyTmV3UXNpRlF4TGZKNVl3dUFqdGhKVWJjRVlUUXRGalBpaXJvSGJmbS8rd25aQ2Zvc05saHRDRjlHV1VEUFFiRU5xbWRVNkxFSXV0RUZyaUlYNWMwMmhnZ0Y1VUQ4eEFkY2QyWXpnR0NidkVJSWdjVGljUjA3NDdpZW9WUHhtSlpGSGdNU2hRUTA5ZW03RGpiRFdrdytkOHJXSUxlazZNaG9iaUg2NFZYdEc3YklMeFZvblBzWmVRSDcvN2M4WUNtL3h4S2IrUW00cXhialBia3BJcW5XallBNlV5WWdhcE1ZVFBBM3RSSUVBamYvOGZEQWM5a2FJMGwyWkRSU3dlTEtPemZlQ3RXRGNDcEdYRHdMNTlTQVg2SUdUN0hVaXdZT1dUOUlrVzkrZHFBemhwWXg1cm4rSy9UOHUzcnNSM2dISlhBRTEyVUNyTkZYaFJYUlN1a2RKVHhhM2dHckR3a1JGaVZ2Wk9BVnhTclVpSEhwWTVpQTlJbXVkOUxSTGpRbDk0a1VtbE9QMVAvN3VlVEhJUHd2elowd0laNVIzZ3M3N0ZOK0NDakIwQ2FicGxoMDBhTXI0VUppUmFOZHdlWUdGV21NNFQ4RU1nY0dnWT0iLCJtYWMiOiI0ZTU4ZmJkNTdkYmY0NGE4NTJjZjlhNDExNzE2YjhlOWM2NTA5OGY2MDA4OTcyZDVlOTljY2JjZDhmMjBhMDUyIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6IkJGMkdRVHRKM2VTcitKNGcvQWJtUGc9PSIsInZhbHVlIjoicmFyRkxPZ1Rybm1ORXlEVjJ2TXFGTzJtM3hWaFhnUVVHN2ZlR1lRM0I5d3ozbnZTcU5EdzJqRkI2elhyNWhlenRTUXV3bjk0N1JXeklDMVAyUzBKcHc9PSIsIm1hYyI6ImJhODVjMGQyZDE3Y2ExNjc2OWVjYWJiNmFjYWVkODIyMTMyNWVhYTExMTgwYTEyMTU0MzUzZGE1YjQ5YzQ5ZjEiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300788C37CDF66ABE9301A68D5D4866AC0C197E04EEE4D904F20A59991322EBAE252301BEF4B24FF01359E934E5654617E4EEAC0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040CEB00EF45BDEA999A5558889E020110802B925F372F7BEFAF0B45E48686113D1DA430ECFCC07B1F61BA6828CC44235278EDB05C486E8068D0BE737D91\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n }\n]","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7498689834597179426
|
6686367646540542029
|
idle
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny_jupiter
Sync Changes
Hide This Notification
Code changed:
Hide
19
19
17
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE id = 1;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;
SELECT * FROM crm_fields WHERE id = 2234;
SELECT * FROM crm_field_values WHERE crm_field_id = 2234;
select * from crm_profiles where user_id = 143;
select * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO
select * from business_processes where crm_configuration_id = 39;
# 01941000000H669AAC, 01941000000H66JAAS
select * from record_type_field_values
where record_type_id IN (24);
select * from crm_field_values where id IN (2730);
select * from crm_configurations where id = 39;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce'; #1035
select * from users where team_id = 1; # 222 group 3
SELECT * FROM activities WHERE user_id = 222 order by id desc;
select * from sidekick_settings where team_id = 1;
select * from teams where id = 1;
select * from team_features where team_id = 1;
select * from activities where crm_configuration_id = 2
and provider = 'ms-teams' and id = 608765;
SELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';
select * from sidekick_settings where team_id = 2;
SELECT * FROM activities WHERE id = 608660;
select * from activity_summary_logs where activity_id = 608660;
select * from ai_prompts where transcription_id = 11214;
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;
# id: 608818, crm: 59628809737
SELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;
# id: 608821, crm: 59632069252
SELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,
playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,
scheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at
FROM activities a
join calendar_events ce on a.calendar_event_id = ce.id
WHERE a.id IN (608818, 608821);
select * from users where team_id = 1;
select * from team_settings where team_id = 1;
select * from crm_profiles where crm_configuration_id = 39 order by user_id;
select * from team_features where team_id = 1;
select * from users where team_id = 2;
SELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639
# Preslava N. Ivanova, grou id 3
SELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;
select * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';
select
a.id,
a.type,
a.scheduled_start_time,
a.actual_start_time,
a.created_at,
a.opportunity_id,
a.status
FROM activities a
WHERE opportunity_id = 344
and status IN ('completed', 'received', 'delivered')
and (
(a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))
;
SELECT * FROM users WHERE id = 222;
SELECT * FROM crm_profiles WHERE user_id = 222;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;
select * from group_deal_risk_types;
select * from opportunities where team_id = 1;
SELECT * FROM opportunities WHERE id = 315;
SELECT * FROM crm_field_data WHERE object_id = 315;
select * from crm_field_data where object_id = 260;
select * from generic_ai_prompts where subject_id = 315;
select * from teams; # 36, 21, 121, [EMAIL]
SELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';
# [PASSWORD_DOTS]
select * from teams where id = 1;
select * from crm_configurations where id = 39;
select * from users where team_id = 1;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 1;
# 1 - 00541000004281rAAA
# 204 - 0052g000003freeAAA
# 429 - 0052g000003qGOiAAM
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
select * from activities where type = 'softphone'
and created_at > '2024-12-11 15:24:36' order by id desc;
select * from activity_providers where team_id = 1;
select * from activity_provider_users where activity_provider_id = 328;
select * from opportunities where crm_configuration_id = 39
AND account_id = 178 AND is_closed = false
order by created_at DESC;
select * from contacts where id = 3952;
select * from accounts where id = 178;
# [PASSWORD_DOTS]
select * from teams where id = 36;
select * from crm_configurations where id = 21;
select * from users where team_id = 36;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 36;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 36
and sa.provider = 'bullhorn';
select * from social_accounts where id = 348;
UPDATE social_accounts SET
provider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',
provider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',
expires = 1733998131,
state = 'connected'
WHERE id = 348;
# [PASSWORD_DOTS]
select * from teams where id = 31;
select * from crm_configurations where id = 18;
select * from users where team_id = 31; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 31;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 31
and sa.provider = 'close';
select * from contacts where crm_configuration_id = 18;
# [PASSWORD_DOTS] NEPTUNE [PASSWORD_DOTS]
select * from teams;
select * from users where id IN (1030, 1035, 1052);
select * from crm_configurations;
select * from users where team_id = 65; # 257
select * from team_settings where team_id = 65; # 257
select * from invitations where team_id = 65; # 257
select * from users where email = '[EMAIL]'; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 65;
select * from crm_configurations where id = 53;
select * from accounts where crm_configuration_id = 53 order by id desc;
select * from leads where crm_configuration_id = 53 order by id desc;
select * from contacts where crm_configuration_id = 53 order by id desc;
select * from opportunities where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 53 order by id desc;
select * from crm_fields where crm_configuration_id = 53 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 53 order by id desc;
select * from stages where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 13;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
and sa.provider = 'integration-app';
select * from contacts where crm_configuration_id = 13;
select * from social_accounts where sociable_id = 283;
SELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';
select * from activity_providers where team_id = 65;
SELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
;
# [PASSWORD_DOTS] STAGING [PASSWORD_DOTS]
SELECT * FROM teams;
SELECT * FROM teams WHERE id = 88;
SELECT * FROM teams WHERE id = 89;
select * from team_settings where team_id = 89;
SELECT * FROM users WHERE team_id = 89;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 89;
select * from users;
SELECT * FROM social_accounts WHERE sociable_id = 1761;
SELECT * FROM crm_configurations WHERE id = 70;
select * from accounts where crm_configuration_id = 70 order by id desc;
select * from leads where crm_configuration_id = 70 order by id desc;
select * from contacts where crm_configuration_id = 70 order by id desc;
select * from opportunities where crm_configuration_id = 70 order by id desc;
select * from crm_profiles where crm_configuration_id = 70 order by id desc;
select * from crm_fields where crm_configuration_id = 70 order by id desc;
select * from crm_field_values where crm_field_id = 3536 order by id desc;
select * from crm_layouts where crm_configuration_id = 70 order by id desc;
select * from stages where crm_configuration_id = 70 order by id desc;
select * from business_processes where crm_configuration_id = 70 order by id desc;
select * from business_process_stages where business_process_id = 34;
select * from contacts where id = 10468;
select * from crm_layouts where crm_configuration_id = 70;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;
SELECT * FROM crm_fields WHERE id IN (3533,3534,3535);
select * from activities where crm_configuration_id = 70
and (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;
SELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;
SELECT * FROM activities where crm_configuration_id = 69 ;
SELECT * FROM users WHERE email LIKE '%[EMAIL]%';
SELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;
SELECT * FROM opportunities WHERE id = 385;
select * from participants p
join activities a on p.activity_id = a.id
where a.crm_configuration_id = 70
and (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);
SELECT * FROM participants WHERE id = 1013638;
select * from teams where id = 90;
select * from users where team_id = 90;
select * from social_accounts where social_accounts.sociable_id IN (1960,1760);
SELECT * FROM crm_profiles WHERE crm_configuration_id = 71;
select * from invitations where team_id = 90;
select * from crm_configurations where id = 71;
select * from accounts where crm_configuration_id = 71 order by id desc;
select * from leads where crm_configuration_id = 71 order by id desc;
select * from contacts where crm_configuration_id = 71 order by id desc;
select * from opportunities where crm_configuration_id = 71 order by id desc;
select * from crm_profiles where crm_configuration_id = 71 order by id desc;
select * from crm_fields where crm_configuration_id = 71 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 71 order by id desc;
select * from stages where crm_configuration_id = 71 order by id desc;
select * from users order by secondary_email desc;
select u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa
join users u on sa.sociable_id = u.id
where sa.provider = 'google' and u.email LIKE 'aneliya%';
select * from failed_jobs order by id desc;
select * from users where email = '[EMAIL]' or secondary_email = '[EMAIL]';
select * from teams;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 39;
SELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;
SELECT * FROM crm_configurations WHERE id = 70;
select * from teams where id = 1;
select * from groups where team_id = 1;
select * from users where team_id = 1;
select o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o
join users u on o.user_id = u.id
join groups g on u.group_id = g.id
join...
|
53084
|
NULL
|
NULL
|
NULL
|
|
53087
|
1861
|
2
|
2026-05-18T11:34:55.649313+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-18/1779 /Users/lukas/.screenpipe/data/data/2026-05-18/1779104095649_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny_jupiter
Sync Changes
Hide This Notification
Code changed:
Hide
19
19
17
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE id = 1;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;
SELECT * FROM crm_fields WHERE id = 2234;
SELECT * FROM crm_field_values WHERE crm_field_id = 2234;
select * from crm_profiles where user_id = 143;
select * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO
select * from business_processes where crm_configuration_id = 39;
# 01941000000H669AAC, 01941000000H66JAAS
select * from record_type_field_values
where record_type_id IN (24);
select * from crm_field_values where id IN (2730);
select * from crm_configurations where id = 39;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce'; #1035
select * from users where team_id = 1; # 222 group 3
SELECT * FROM activities WHERE user_id = 222 order by id desc;
select * from sidekick_settings where team_id = 1;
select * from teams where id = 1;
select * from team_features where team_id = 1;
select * from activities where crm_configuration_id = 2
and provider = 'ms-teams' and id = 608765;
SELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';
select * from sidekick_settings where team_id = 2;
SELECT * FROM activities WHERE id = 608660;
select * from activity_summary_logs where activity_id = 608660;
select * from ai_prompts where transcription_id = 11214;
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;
# id: 608818, crm: 59628809737
SELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;
# id: 608821, crm: 59632069252
SELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,
playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,
scheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at
FROM activities a
join calendar_events ce on a.calendar_event_id = ce.id
WHERE a.id IN (608818, 608821);
select * from users where team_id = 1;
select * from team_settings where team_id = 1;
select * from crm_profiles where crm_configuration_id = 39 order by user_id;
select * from team_features where team_id = 1;
select * from users where team_id = 2;
SELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639
# Preslava N. Ivanova, grou id 3
SELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;
select * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';
select
a.id,
a.type,
a.scheduled_start_time,
a.actual_start_time,
a.created_at,
a.opportunity_id,
a.status
FROM activities a
WHERE opportunity_id = 344
and status IN ('completed', 'received', 'delivered')
and (
(a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))
;
SELECT * FROM users WHERE id = 222;
SELECT * FROM crm_profiles WHERE user_id = 222;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;
select * from group_deal_risk_types;
select * from opportunities where team_id = 1;
SELECT * FROM opportunities WHERE id = 315;
SELECT * FROM crm_field_data WHERE object_id = 315;
select * from crm_field_data where object_id = 260;
select * from generic_ai_prompts where subject_id = 315;
select * from teams; # 36, 21, 121, [EMAIL]
SELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';
# [PASSWORD_DOTS]
select * from teams where id = 1;
select * from crm_configurations where id = 39;
select * from users where team_id = 1;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 1;
# 1 - 00541000004281rAAA
# 204 - 0052g000003freeAAA
# 429 - 0052g000003qGOiAAM
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
select * from activities where type = 'softphone'
and created_at > '2024-12-11 15:24:36' order by id desc;
select * from activity_providers where team_id = 1;
select * from activity_provider_users where activity_provider_id = 328;
select * from opportunities where crm_configuration_id = 39
AND account_id = 178 AND is_closed = false
order by created_at DESC;
select * from contacts where id = 3952;
select * from accounts where id = 178;
# [PASSWORD_DOTS]
select * from teams where id = 36;
select * from crm_configurations where id = 21;
select * from users where team_id = 36;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 36;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 36
and sa.provider = 'bullhorn';
select * from social_accounts where id = 348;
UPDATE social_accounts SET
provider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',
provider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',
expires = 1733998131,
state = 'connected'
WHERE id = 348;
# [PASSWORD_DOTS]
select * from teams where id = 31;
select * from crm_configurations where id = 18;
select * from users where team_id = 31; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 31;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 31
and sa.provider = 'close';
select * from contacts where crm_configuration_id = 18;
# [PASSWORD_DOTS] NEPTUNE [PASSWORD_DOTS]
select * from teams;
select * from users where id IN (1030, 1035, 1052);
select * from crm_configurations;
select * from users where team_id = 65; # 257
select * from team_settings where team_id = 65; # 257
select * from invitations where team_id = 65; # 257
select * from users where email = '[EMAIL]'; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 65;
select * from crm_configurations where id = 53;
select * from accounts where crm_configuration_id = 53 order by id desc;
select * from leads where crm_configuration_id = 53 order by id desc;
select * from contacts where crm_configuration_id = 53 order by id desc;
select * from opportunities where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 53 order by id desc;
select * from crm_fields where crm_configuration_id = 53 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 53 order by id desc;
select * from stages where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 13;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
and sa.provider = 'integration-app';
select * from contacts where crm_configuration_id = 13;
select * from social_accounts where sociable_id = 283;
SELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';
select * from activity_providers where team_id = 65;
SELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
;
# [PASSWORD_DOTS] STAGING [PASSWORD_DOTS]
SELECT * FROM teams;
SELECT * FROM teams WHERE id = 88;
SELECT * FROM teams WHERE id = 89;
select * from team_settings where team_id = 89;
SELECT * FROM users WHERE team_id = 89;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 89;
select * from users;
SELECT * FROM social_accounts WHERE sociable_id = 1761;
SELECT * FROM crm_configurations WHERE id = 70;
select * from accounts where crm_configuration_id = 70 order by id desc;
select * from leads where crm_configuration_id = 70 order by id desc;
select * from contacts where crm_configuration_id = 70 order by id desc;
select * from opportunities where crm_configuration_id = 70 order by id desc;
select * from crm_profiles where crm_configuration_id = 70 order by id desc;
select * from crm_fields where crm_configuration_id = 70 order by id desc;
select * from crm_field_values where crm_field_id = 3536 order by id desc;
select * from crm_layouts where crm_configuration_id = 70 order by id desc;
select * from stages where crm_configuration_id = 70 order by id desc;
select * from business_processes where crm_configuration_id = 70 order by id desc;
select * from business_process_stages where business_process_id = 34;
select * from contacts where id = 10468;
select * from crm_layouts where crm_configuration_id = 70;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;
SELECT * FROM crm_fields WHERE id IN (3533,3534,3535);
select * from activities where crm_configuration_id = 70
and (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;
SELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;
SELECT * FROM activities where crm_configuration_id = 69 ;
SELECT * FROM users WHERE email LIKE '%[EMAIL]%';
SELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;
SELECT * FROM opportunities WHERE id = 385;
select * from participants p
join activities a on p.activity_id = a.id
where a.crm_configuration_id = 70
and (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);
SELECT * FROM participants WHERE id = 1013638;
select * from teams where id = 90;
select * from users where team_id = 90;
select * from social_accounts where social_accounts.sociable_id IN (1960,1760);
SELECT * FROM crm_profiles WHERE crm_configuration_id = 71;
select * from invitations where team_id = 90;
select * from crm_configurations where id = 71;
select * from accounts where crm_configuration_id = 71 order by id desc;
select * from leads where crm_configuration_id = 71 order by id desc;
select * from contacts where crm_configuration_id = 71 order by id desc;
select * from opportunities where crm_configuration_id = 71 order by id desc;
select * from crm_profiles where crm_configuration_id = 71 order by id desc;
select * from crm_fields where crm_configuration_id = 71 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 71 order by id desc;
select * from stages where crm_configuration_id = 71 order by id desc;
select * from users order by secondary_email desc;
select u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa
join users u on sa.sociable_id = u.id
where sa.provider = 'google' and u.email LIKE 'aneliya%';
select * from failed_jobs order by id desc;
select * from users where email = '[EMAIL]' or secondary_email = '[EMAIL]';
select * from teams;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 39;
SELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;
SELECT * FROM crm_configurations WHERE id = 70;
select * from teams where id = 1;
select * from groups where team_id = 1;
select * from users where team_id = 1;
select o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o
join users u on o.user_id = u.id
join groups g on u.group_id = g.id
join...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>114 incoming commits<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.3929521,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.40292552,"top":0.10055866,"width":0.00731383,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.4119016,"top":0.09896249,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.4192154,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\n\nuse Illuminate\\Database\\Eloquent;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\ElasticSearch\\Model\\Observer;\nuse Jiminny\\Component\\Twilio\\Conference\\ConferenceManager;\nuse Jiminny\\Component\\Twilio\\Exception\\OutOfBoundsException;\nuse Jiminny\\Component\\Twilio\\Exception\\UnexpectedValueException;\nuse Jiminny\\Component\\Twilio\\Resolver;\nuse Jiminny\\Component\\Twilio\\VO;\nuse Jiminny\\Component\\UrlGenerator\\Webhook;\nuse Jiminny\\Events;\nuse Jiminny\\Exceptions\\LogicException;\nuse Jiminny\\Models;\nuse Jiminny\\Models\\Participant\\Connection;\nuse Jiminny\\Services\\ActivityService;\nuse Jiminny\\Services\\Activity\\CrmOwnerResolver;\nuse Jiminny\\Services\\Crm\\CachedCrmServiceDecorator;\nuse Jiminny\\Services\\Crm\\ProviderRegistry;\nuse Jiminny\\Services\\Telephony\\TwilioClientBuilder;\nuse Psr\\Log\\LoggerInterface;\nuse Twilio\\Exceptions\\ConfigurationException;\nuse Twilio\\Exceptions\\RestException;\nuse Twilio\\Exceptions\\TwilioException;\nuse Twilio\\TwiML;\n\nfinal readonly class SoftPhoneManager implements ConferenceManager\n{\n public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;\n public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';\n\n public function __construct(\n private ProviderRegistry $crmProviderRegistry,\n private Webhook $urlGenerator,\n private ActivityService $activityService,\n private LoggerInterface $logger,\n private TwilioClientBuilder $twilioClientBuilder,\n ) {\n }\n\n public function create(VO\\ConferenceManager\\ActivityCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n 'instanceof' => get_class($data),\n ]);\n\n $activity = Observer::skipEvents(function () use ($data) {\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundCreate) {\n $activity = $this->createInboundActivity($data);\n } elseif ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundCreate) {\n $activity = $this->createOutboundActivity($data);\n } else {\n throw new LogicException(sprintf(\n 'Unknown softphone implementation: %s',\n get_class($data)\n ));\n }\n\n return $activity;\n });\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'instanceof' => get_class($data),\n 'activity' => $activity->id_string,\n ]);\n\n return $activity;\n }\n\n private function createOutboundActivity(VO\\ConferenceManager\\SoftPhoneOutboundCreate $data): Models\\Activity\n {\n $startTime = microtime(true);\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n $now = now();\n $user = $data->getUser();\n $team = $user->getTeam();\n $device = $data->getDevice();\n $phoneNumber = $data->getPhoneNumber();\n $route = $data->getPhoneRoute();\n\n if (! $this->activityService->teamCanDial($team, $phoneNumber)) {\n $region = getRegionByNumber($phoneNumber, $user->getCountryCode());\n\n throw new LogicException(sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? 'this number'\n ));\n }\n\n $lead = null;\n $account = null;\n $contact = null;\n $stage = null;\n $opportunity = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $team,\n 'integrationAdmin' => $user,\n 'providerSlug' => $team->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n } catch (\\Throwable $throwable) {\n $this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [\n 'exception' => $throwable,\n 'user_id' => $user->getId(),\n 'team_id' => $team->getId(),\n ]);\n $crmService = $this->crmProviderRegistry->get($team->crm->provider);\n if (! $user->isCrmRequired()) {\n $crmService->setUser($user->team->owner);\n } else {\n $crmService->setUser($user);\n }\n }\n\n $prospectId = $data->getProspectId();\n\n try {\n if ($prospectId !== null) {\n $crmStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [\n 'prospect_id' => $prospectId,\n 'object_type' => $data->getObjectType(),\n ]);\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(\n $prospectId,\n $data->getObjectType()\n );\n $this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),\n 'found_lead' => $lead !== null,\n 'found_account' => $account !== null,\n 'found_opportunity' => $opportunity !== null,\n 'found_contact' => $contact !== null,\n ]);\n\n // Try to attach a contact if we have an opportunity.\n if ($opportunity !== null && $contact === null) {\n $matchStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');\n [, , , $contact, ] = $crmService->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n $this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),\n 'found_contact' => $contact !== null,\n ]);\n }\n } else {\n $decorator = resolve(CachedCrmServiceDecorator::class);\n $decorator->setCrmService($crmService);\n\n [$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(\n $data->getPhoneNumber(),\n $data->getRawPhoneNumber(),\n $user->getId()\n );\n }\n } catch (\\Throwable $throwable) {\n $this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.\n }\n\n if ($data->hasProspectStage()) {\n /** @var Models\\Stage $stage */\n $stage = $team->crm->stages()->uuid($data->getProspectStage());\n }\n\n $dbStart = microtime(true);\n $this->logger->info('[SoftPhoneManager] Starting activity creation in DB');\n $activity = $user->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'device_id' => $device->id ?? null,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'value' => $opportunity ? $opportunity->value : null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_PENDING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),\n 'scheduled_start_time' => $now,\n ]);\n $this->logger->info('[SoftPhoneManager] Activity created in DB', [\n 'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),\n 'activity_id' => $activity->id ?? null,\n ]);\n\n if (! $activity instanceof Models\\Activity) {\n throw new LogicException('Activity model expected');\n }\n\n $regionId = null;\n if ($user->hasRegionId()) {\n $regionId = $user->getRegionId();\n } elseif ($data->hasRegion()) {\n $regionId = $data->getRegion()->getId();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $regionId,\n 'is_muted' => false,\n ]);\n\n $phoneRouteResolver = new Resolver\\PhoneRouteResolver($user, $route);\n $phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();\n $connectionType = $phoneRouteResolver->getConnectionType();\n $callerId = $this->determineUserCallerId($user);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'user_id' => $user->id,\n 'email' => $user->email,\n 'name' => $user->name,\n 'phone_number' => $phoneRouteResolver->mustUsePSTN()\n ? $phoneNumberOrigin\n : $callerId,\n ]);\n\n $caller->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',\n 'phone' => $callerId,\n 'type' => $connectionType,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $phoneNumber,\n 'name' => $activity->prospect_name,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'phone' => $phoneNumber,\n 'direction' => 'outbound-api',\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $activity->refresh();\n\n $this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [\n 'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),\n 'activity_id' => $activity->id_string,\n ]);\n $this->logger->debug(__METHOD__ . ': done', [\n 'data' => $data,\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n return $activity;\n }\n\n private function createInboundActivity(VO\\ConferenceManager\\SoftPhoneInboundCreate $data): Models\\Activity\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $roomOwner = $data->getUser();\n $team = $roomOwner->getTeam();\n $phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();\n $callerId = $data->getCallerId();\n $callerCallSid = $data->getCallSid();\n\n $now = now();\n\n if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {\n $region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());\n\n throw new LogicException(\n sprintf(\n 'Sorry, dialing %s is not available with your subscription.'\n . ' Please contact your manager to enable additional destinations.',\n $region ?? ' this number',\n ),\n );\n }\n\n $lead = $account = $opportunity = $contact = $stage = null;\n\n try {\n $crmResolver = app(CrmOwnerResolver::class, [\n 'team' => $roomOwner->getTeam(),\n 'integrationAdmin' => $roomOwner,\n 'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),\n ]);\n $crmService = $crmResolver->prepareCrmService();\n\n [$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(\n $callerId,\n null,\n $roomOwner->getId()\n );\n } catch (\\Throwable $throwable) {\n $this->logger->error(__METHOD__ . ': crm exception', [\n 'exception' => $throwable,\n ]);\n // maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening\n }\n\n /** @var Models\\Activity $activity */\n $activity = $roomOwner->activities()->create([\n 'type' => Models\\Activity::TYPE_SOFTPHONE_INBOUND,\n 'provider' => Models\\Activity::PROVIDER_TWILIO,\n 'crm_configuration_id' => $team->crm_id,\n 'lead_id' => $lead->id ?? null,\n 'account_id' => $account->id ?? null,\n 'contact_id' => $contact->id ?? null,\n 'opportunity_id' => $opportunity->id ?? null,\n 'stage_id' => $stage->id ?? null,\n 'status' => Models\\Activity::STATUS_RINGING,\n 'recording_state' => Models\\Activity::RECORDING_OFF,\n 'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),\n 'scheduled_start_time' => $now,\n ]);\n\n /** @var Models\\Session $session */\n $session = $activity->sessions()->create([\n 'type' => Models\\Session::TYPE_DIALER,\n 'region_id' => $roomOwner->getRegionId(),\n 'is_muted' => false,\n ]);\n\n /** @var Models\\Participant $caller */\n $caller = $activity->participants()->create([\n 'lead_id' => $activity->lead_id ?? null,\n 'contact_id' => $activity->contact_id ?? null,\n 'phone_number' => $callerId,\n 'name' => $activity->prospect_name,\n 'enter_time' => $now,\n ]);\n\n $caller->connections()->create([\n 'telephony_provider_id' => $callerCallSid,\n 'session_id' => $session->getId(),\n 'phone' => $callerId,\n 'direction' => 'inbound',\n 'type' => Connection::TYPE_PSTN,\n 'opened_at' => $now,\n ]);\n\n /** @var Models\\Participant $callee */\n $callee = $activity->participants()->create([\n 'user_id' => $roomOwner->id,\n 'email' => $roomOwner->email,\n 'name' => $roomOwner->name,\n 'phone_number' => $phoneNumber,\n ]);\n\n $callee->connections()->create([\n 'session_id' => $session->getId(),\n 'direction' => 'outbound-api',\n 'phone' => $phoneNumber,\n 'type' => Connection::TYPE_PSTN,\n ]);\n\n $activity->update([\n 'from_participant_id' => $caller->id,\n 'to_participant_id' => $callee->id,\n ]);\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'callSid' => $data->getCallSid(),\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n 'caller' => $caller->id_string,\n 'callee' => $callee->id_string,\n ]);\n\n $activity->refresh();\n\n return $activity;\n }\n\n private function getVoiceRecordingReasonCode(Models\\Team $team, string $phoneNumber): int\n {\n $this->logger->debug(__METHOD__, [\n 'team' => $team->id_string,\n 'phone' => $phoneNumber,\n ]);\n\n if (\n ! $team->hasComplianceModeRecordingPrompt()\n && ! $team->hasComplianceModeRecordingRestrictToOneSide()\n && ! $team->hasComplianceModeRecordingRestrictRecording()\n ) {\n return 0;\n }\n\n /** @var Models\\VoiceConsentPrefix|null $voiceConsentPolicy */\n $voiceConsentPolicy = Models\\VoiceConsentPrefix::query()\n ->whereRaw(\"? LIKE CONCAT(destination_prefix, '%')\", [$phoneNumber])\n ->where(static function (Eloquent\\Builder $builder) use ($team): void {\n $builder\n ->whereNull('team_id')\n ->orWhere('team_id', $team->getId());\n })\n ->orderByDesc('team_id')\n ->first();\n\n if (! $voiceConsentPolicy instanceof Models\\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {\n return 0;\n }\n\n if ($team->hasComplianceModeRecordingPrompt()) {\n // This number requires consent from the other party before recording the call.\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;\n }\n\n if ($team->hasComplianceModeRecordingRestrictToOneSide()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;\n }\n\n if ($team->hasComplianceModeRecordingRestrictRecording()) {\n return Models\\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;\n }\n\n return 0;\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOrganiser(Models\\Activity $activity): void\n {\n $this->logger->debug(__METHOD__, [\n 'activity' => $activity->id_string,\n ]);\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $canBeDialed =\n $activity->isTypeSoftPhone()\n && ! $activity->hasStarted()\n && $activity->isPending()\n && $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->exists();\n\n if (! $canBeDialed) {\n throw new OutOfBoundsException('Cannot make an outbound call to this activity.');\n }\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->where('type', '=', Connection::TYPE_PSTN)\n ->whereNull('opened_at')\n ->firstOrFail();\n\n /** @var Models\\Session $session */\n $session = $organiserConnection->getSession();\n\n $twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ]);\n\n // What number will the organizer see as caller id\n $callerId = $roomOwner->getSoftPhoneNumber();\n\n if ($callerId === null) {\n $callee = $activity->participants()->whereNull('user_id')->first();\n // This is a bridge call. We make it look like the callee is calling the organizer\n $callerId = $callee->phone_number;\n }\n\n // What number will the prospect see as caller id\n $calleeId = $organiser->getPhoneNumber();\n\n $this->logger->debug(__METHOD__ . ': twilio call', [\n 'calleeId' => $calleeId,\n 'callerId' => $callerId,\n ]);\n\n $twilioParticipant = $twilio->createParticipantInstance(\n $session->id_string,\n $callerId,\n $calleeId,\n $twilioConferenceSettings\n );\n\n $organiserConnection\n ->setTelephonyProviderId($twilioParticipant->callSid)\n ->save();\n\n $session\n ->setTelephonyProviderId($twilioParticipant->conferenceSid)\n ->save();\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function dialCoach(Models\\Activity $activity, Models\\User $user): void\n {\n throw new \\LogicException('Not implemented yet');\n }\n\n /**\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function terminate(VO\\ConferenceManager\\ActivityTerminate $data): void\n {\n if (! $data instanceof VO\\ConferenceManager\\SoftphoneTerminate) {\n throw new UnexpectedValueException(sprintf(\n 'Expecting an instance of \"%s\", but \"%s\" given.',\n VO\\ConferenceManager\\SoftphoneTerminate::class,\n \\get_class($data)\n ));\n }\n\n $this->logger->debug(__METHOD__, [\n 'activity' => $data->getActivity()->id_string,\n 'user' => $data->getUser()->id_string,\n ]);\n\n $activity = $data->getActivity();\n $roomOwner = $activity->getUser();\n\n $isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();\n\n if ($isCancelling) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n }\n\n /** @var Models\\Session $session */\n $session = $activity->sessions->first();\n\n /** @var Models\\Participant $organiser */\n $organiser = $activity->organizer;\n\n /** @var Connection $organiserConnection */\n $organiserConnection = $organiser->connections()\n ->whereIn('type', [\n Connection::TYPE_WEBRTC,\n Connection::TYPE_PSTN,\n ])\n ->firstOrFail();\n\n if (! $organiserConnection->hasTelephonyProviderId()) {\n throw new LogicException(\n 'Unable to terminate call as we do not yet know the organiser telephony provider id',\n );\n }\n\n $twilioClient = $this->twilioClientBuilder->build($activity->getTeam());\n\n $twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());\n\n $session->hasTelephonyProviderId()\n && $twilioClient->terminateConference($session->getTelephonyProviderId());\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'session' => $session->id_string,\n ]);\n }\n\n public function answer(VO\\ConferenceManager\\ActivityAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'data' => $data,\n ]);\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneInboundAnswer) {\n return $this->answerInboundCall($data);\n }\n\n if ($data instanceof VO\\ConferenceManager\\SoftPhoneOutboundAnswer) {\n return $this->answerOutboundCall($data);\n }\n\n throw new LogicException('Unable to answer - not supported activity answer instance');\n }\n\n private function answerInboundCall(VO\\ConferenceManager\\SoftPhoneInboundAnswer $data): TwiML\\VoiceResponse\n {\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n ]);\n\n $dateTime = now();\n\n $activity = $this->create(\n new VO\\ConferenceManager\\SoftPhoneInboundCreate(\n $data->getCallerId(),\n $data->getCallSid(),\n $data->getUser()\n )\n );\n\n /** @var Models\\Participant $activityGuest */\n $activityGuest = $activity->from;\n\n $activityGuest\n ->setEnterTime($dateTime)\n ->save();\n\n /** @var Connection $connection */\n $connection = $activityGuest->connections()\n ->where('type', Connection::TYPE_PSTN)\n ->firstOrFail();\n\n $connection\n ->setTelephonyProviderId($data->getCallSid())\n ->setOpenedAt($dateTime)\n ->save();\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n return $this->joinTwilioConference($connection, [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]);\n }\n\n private function answerOutboundCall(VO\\ConferenceManager\\SoftPhoneOutboundAnswer $data): TwiML\\VoiceResponse\n {\n $connection = $data->getConnection();\n $participant = $connection->getParticipant();\n $activity = $data->getActivity();\n $organiser = $activity->organizer;\n $dateTime = now();\n\n $this->logger->debug(__METHOD__, [\n 'callSid' => $data->getCallSid(),\n 'connection' => $connection->id_string,\n 'participant' => $participant->id_string,\n 'activity' => $activity->id_string,\n ]);\n\n if (! $participant->hasEnterTime()) {\n $participant->update([\n 'enter_time' => $dateTime,\n ]);\n }\n\n $connection->update([\n 'is_muted' => $participant->isCoach(),\n 'opened_at' => $dateTime,\n ]);\n\n event(new Events\\Activities\\Connections\\Opened($connection));\n\n if ($participant->isCoach()) {\n /** @var Connection $roomOwnerConnection */\n $roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'coach' => $roomOwnerConnection->getTelephonyProviderId(),\n ]\n );\n }\n\n return $this->joinTwilioConference(\n $connection,\n [\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n 'muted' => false,\n ]\n );\n }\n\n private function determineUserCallerId(Models\\User $user): string\n {\n if ($user->hasCallerId()) {\n return $user->getCallerId();\n }\n\n // TODO: We should require a caller id to be verified before using the dialer\n return $user->getSoftPhoneNumber() ?? $user->phone;\n }\n\n private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool\n {\n $startsWith = '[HTTP 404] Unable to create record: The requested resource';\n $endsWith = 'was not found';\n\n return Str::startsWith($exceptionMessage, $startsWith)\n && Str::endsWith($exceptionMessage, $endsWith);\n }\n\n /**\n * @throws RestException\n * @throws ConfigurationException\n * @throws TwilioException\n */\n public function dialOtherParty(Connection $callerConnection): self\n {\n $session = $callerConnection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n $twilio = $this->twilioClientBuilder->build($activity->getTeam());\n\n $this->logger->debug(__METHOD__, [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {\n throw new UnexpectedValueException('Unexpected activity type');\n }\n\n $callee = $activity->to;\n $calleeId = $callee->getPhoneNumber();\n\n /** @var Connection $calleeConnection */\n $calleeConnection = $callee->connections()\n ->whereIn('type', [\n Connection::TYPE_PSTN,\n Connection::TYPE_WEBRTC,\n ])\n ->firstOrFail();\n\n $caller = $activity->from;\n\n // we need to take the number from the connection\n // as the one we store on participant level might be the one we call to the rep via PSTN mode\n $callerId = $callerConnection->getPhoneNumber();\n\n if (! $caller->is($callerConnection->getParticipant())) {\n throw new LogicException(sprintf(\n 'Unexpected caller participant. Expected: \"%s\", Actual: \"%s\"',\n $caller->id_string,\n $callerConnection->getParticipant()->id_string\n ));\n }\n\n $twilioConferenceSettings = [\n 'muted' => false,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => true,\n ];\n\n $hasInboundRecording = $activity->isTypeSoftphoneInbound()\n && $roomOwner->checkSoftphoneInboundRecordPreference();\n\n $hasOutboundRecording = $activity->isTypeSoftPhone()\n && $roomOwner->checkSoftphoneOutboundRecordPreference();\n\n $isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;\n\n $isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()\n || $activity->hasRecordingReasonComplianceRestricted();\n\n if ($isRecordingEnabled && ! $isRecordingRestricted) {\n $twilioConferenceSettings = array_merge($twilioConferenceSettings, [\n 'record' => true,\n 'recordingChannels' => 'dual',\n 'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),\n 'recordingStatusCallbackMethod' => 'POST',\n 'recordingStatusCallbackEvent' => 'in-progress completed absent',\n ]);\n\n if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {\n $twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()\n ? 'outbound'\n : 'inbound';\n }\n }\n\n try {\n if ($activity->hasRecordingReasonCompliancePrompted()) {\n $this->logger->info('[Softphone] Request compliance prompt via outbound call', [\n 'activity_uuid' => $activity->getUuid(),\n 'session' => $session->id_string,\n 'conference_sid' => $session->getTelephonyProviderId(),\n ]);\n\n $callInstance = $twilio->createCall(\n $callerId,\n $calleeId,\n $this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [\n 'session' => $session->id_string,\n 'connection' => $calleeConnection->id_string,\n ]),\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $callInstance->sid,\n 'parent_connection_id' => $callerConnection->getId(),\n ]);\n } else {\n $twilioParticipantConnection = $twilio->createParticipantInstance(\n $session->getTelephonyProviderId(),\n $callerId,\n $calleeId,\n $this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)\n );\n\n $calleeConnection->update([\n 'telephony_provider_id' => $twilioParticipantConnection->callSid,\n ]);\n }\n } catch (RestException $restException) {\n if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {\n throw $restException;\n }\n\n if (! $activity->isInFiniteState()) {\n $activity\n ->setStatus(Models\\Activity::STATUS_CANCELLED)\n ->save();\n\n $message = __METHOD__ . ': activity.status -> cancelled';\n } else {\n $message = sprintf(\n __METHOD__ . ': not setting to cancelled, activity.status is %s',\n $activity->getStatus()\n );\n }\n\n $this->logger->info($message, [\n 'activity' => $activity->id_string,\n 'exception' => $restException,\n ]);\n }\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n 'connection' => $callerConnection->id_string,\n ]);\n\n return $this;\n }\n\n private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array\n {\n $session = $connection->getSession();\n\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => true,\n 'endConferenceOnExit' => false,\n 'record' => false,\n 'waitUrl' => '',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]),\n 'statusCallbackEvent' => [\n 'initiated',\n 'ringing',\n 'answered',\n 'completed',\n ],\n 'statusCallbackMethod' => 'POST',\n 'conferenceStatusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n ]),\n 'conferenceStatusCallbackMethod' => 'POST',\n 'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function applyDefaultTwilioConferenceSettings(Models\\Session $session, array $override = []): array\n {\n $default = [\n 'beep' => false,\n 'muted' => true,\n 'startConferenceOnEnter' => false,\n 'endConferenceOnExit' => false,\n 'waitUrl' => '',\n 'statusCallbackEvent' => implode(' ', [\n 'start',\n 'end',\n 'join',\n 'leave',\n 'mute',\n 'hold',\n// 'speaker',\n ]),\n 'statusCallbackMethod' => 'POST',\n 'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [\n 'session' => $session->getIdString(),\n ]),\n ];\n\n if ($session->hasRegion()) {\n $default['region'] = $session->getRegion()->getName();\n }\n\n return array_merge($default, $override);\n }\n\n private function joinTwilioConference(Connection $connection, array $options = []): TwiML\\VoiceResponse\n {\n $session = $connection->getSession();\n $activity = $session->getActivity();\n $roomOwner = $activity->getUser();\n\n $this->logger->debug(__METHOD__, [\n 'connection' => $connection->id_string,\n 'session' => $session->id_string,\n 'activity' => $activity->id_string,\n 'user' => $roomOwner->id_string,\n ]);\n\n $voiceResponse = new TwiML\\VoiceResponse();\n\n $voiceResponse->dial()\n ->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [\n 'connection' => $connection->id_string,\n ]))\n ->conference(\n $session->getIdString(),\n $this->applyDefaultTwilioConferenceSettings($session, $options)\n );\n\n $this->logger->debug(__METHOD__ . ': done', [\n 'session' => $session->id_string,\n 'result' => $voiceResponse,\n ]);\n\n return $voiceResponse;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.42785904,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.43650267,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.4474734,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.45611703,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.46476063,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.47573137,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.4867021,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.51329786,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5242686,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny_jupiter","depth":4,"bounds":{"left":0.69348407,"top":0.09896249,"width":0.04089096,"height":0.01915403},"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":"19","depth":4,"bounds":{"left":0.6871675,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"19","depth":4,"bounds":{"left":0.6988032,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"17","depth":4,"bounds":{"left":0.71043885,"top":0.123703115,"width":0.00930851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.72140956,"top":0.12210695,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.7287234,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM teams WHERE id = 1;\n\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;\nSELECT * FROM crm_fields WHERE id = 2234;\nSELECT * FROM crm_field_values WHERE crm_field_id = 2234;\n\nselect * from crm_profiles where user_id = 143;\n\nselect * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO\nselect * from business_processes where crm_configuration_id = 39;\n# 01941000000H669AAC, 01941000000H66JAAS\n\nselect * from record_type_field_values\n where record_type_id IN (24);\n\nselect * from crm_field_values where id IN (2730);\n\nselect * from crm_configurations where id = 39;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce'; #1035\n\n\nselect * from users where team_id = 1; # 222 group 3\nSELECT * FROM activities WHERE user_id = 222 order by id desc;\nselect * from sidekick_settings where team_id = 1;\nselect * from teams where id = 1;\nselect * from team_features where team_id = 1;\n\nselect * from activities where crm_configuration_id = 2\nand provider = 'ms-teams' and id = 608765;\n\nSELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';\n\nselect * from sidekick_settings where team_id = 2;\n\nSELECT * FROM activities WHERE id = 608660;\nselect * from activity_summary_logs where activity_id = 608660;\nselect * from ai_prompts where transcription_id = 11214;\n\n# ********************************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;\n# id: 608818, crm: 59628809737\nSELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;\n# id: 608821, crm: 59632069252\nSELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,\nplaybook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,\nscheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at\nFROM activities a\njoin calendar_events ce on a.calendar_event_id = ce.id\nWHERE a.id IN (608818, 608821);\n\nselect * from users where team_id = 1;\nselect * from team_settings where team_id = 1;\nselect * from crm_profiles where crm_configuration_id = 39 order by user_id;\n\nselect * from team_features where team_id = 1;\n\nselect * from users where team_id = 2;\n\nSELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639\n# Preslava N. Ivanova, grou id 3\n\nSELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;\n\nselect * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';\n\nselect\n a.id,\n a.type,\n a.scheduled_start_time,\n a.actual_start_time,\n a.created_at,\n a.opportunity_id,\n a.status\nFROM activities a\nWHERE opportunity_id = 344\nand status IN ('completed', 'received', 'delivered')\nand (\n (a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))\n;\n\nSELECT * FROM users WHERE id = 222;\n\nSELECT * FROM crm_profiles WHERE user_id = 222;\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;\n\nselect * from group_deal_risk_types;\n\nselect * from opportunities where team_id = 1;\n\nSELECT * FROM opportunities WHERE id = 315;\nSELECT * FROM crm_field_data WHERE object_id = 315;\nselect * from crm_field_data where object_id = 260;\n\nselect * from generic_ai_prompts where subject_id = 315;\n\nselect * from teams; # 36, 21, 121, james.graham@bullhorn.jiminny.com\nSELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';\n\n# ************************************************************************************\nselect * from teams where id = 1;\nselect * from crm_configurations where id = 39;\nselect * from users where team_id = 1;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 1;\n# 1 - 00541000004281rAAA\n# 204 - 0052g000003freeAAA\n# 429 - 0052g000003qGOiAAM\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\nselect * from activities where type = 'softphone'\nand created_at > '2024-12-11 15:24:36' order by id desc;\n\nselect * from activity_providers where team_id = 1;\nselect * from activity_provider_users where activity_provider_id = 328;\n\nselect * from opportunities where crm_configuration_id = 39\nAND account_id = 178 AND is_closed = false\norder by created_at DESC;\n\nselect * from contacts where id = 3952;\nselect * from accounts where id = 178;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations where id = 21;\nselect * from users where team_id = 36;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 36;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 36\nand sa.provider = 'bullhorn';\n\nselect * from social_accounts where id = 348;\nUPDATE social_accounts SET\nprovider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',\nprovider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',\nexpires = 1733998131,\nstate = 'connected'\nWHERE id = 348;\n\n# ************************************************************************************\nselect * from teams where id = 31;\nselect * from crm_configurations where id = 18;\n\nselect * from users where team_id = 31; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 31;\n\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 31\nand sa.provider = 'close';\n\nselect * from contacts where crm_configuration_id = 18;\n\n# ********************** NEPTUNE **************************************************************\nselect * from teams;\nselect * from users where id IN (1030, 1035, 1052);\nselect * from crm_configurations;\n\nselect * from users where team_id = 65; # 257\nselect * from team_settings where team_id = 65; # 257\nselect * from invitations where team_id = 65; # 257\nselect * from users where email = 'integration-account@jiminny.com'; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 65;\n\nselect * from crm_configurations where id = 53;\nselect * from accounts where crm_configuration_id = 53 order by id desc;\nselect * from leads where crm_configuration_id = 53 order by id desc;\nselect * from contacts where crm_configuration_id = 53 order by id desc;\nselect * from opportunities where crm_configuration_id = 53 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 53 order by id desc;\nselect * from crm_fields where crm_configuration_id = 53 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 53 order by id desc;\nselect * from stages where crm_configuration_id = 53 order by id desc;\n\n\nselect * from crm_profiles where crm_configuration_id = 13;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\nand sa.provider = 'integration-app';\n\nselect * from contacts where crm_configuration_id = 13;\n\nselect * from social_accounts where sociable_id = 283;\n\nSELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';\n\nselect * from activity_providers where team_id = 65;\nSELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\n;\n\n# ***************************** STAGING ********************************************\nSELECT * FROM teams;\nSELECT * FROM teams WHERE id = 88;\nSELECT * FROM teams WHERE id = 89;\nselect * from team_settings where team_id = 89;\nSELECT * FROM users WHERE team_id = 89;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 89;\n\nselect * from users;\nSELECT * FROM social_accounts WHERE sociable_id = 1761;\nSELECT * FROM crm_configurations WHERE id = 70;\nselect * from accounts where crm_configuration_id = 70 order by id desc;\nselect * from leads where crm_configuration_id = 70 order by id desc;\nselect * from contacts where crm_configuration_id = 70 order by id desc;\nselect * from opportunities where crm_configuration_id = 70 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 70 order by id desc;\nselect * from crm_fields where crm_configuration_id = 70 order by id desc;\nselect * from crm_field_values where crm_field_id = 3536 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 70 order by id desc;\nselect * from stages where crm_configuration_id = 70 order by id desc;\nselect * from business_processes where crm_configuration_id = 70 order by id desc;\nselect * from business_process_stages where business_process_id = 34;\n\nselect * from contacts where id = 10468;\n\nselect * from crm_layouts where crm_configuration_id = 70;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;\nSELECT * FROM crm_fields WHERE id IN (3533,3534,3535);\n\nselect * from activities where crm_configuration_id = 70\nand (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;\n\nSELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;\nSELECT * FROM activities where crm_configuration_id = 69 ;\n\nSELECT * FROM users WHERE email LIKE '%jiminny_web_sa2@jiminny.com%';\nSELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;\nSELECT * FROM opportunities WHERE id = 385;\n\nselect * from participants p\njoin activities a on p.activity_id = a.id\nwhere a.crm_configuration_id = 70\nand (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);\nSELECT * FROM participants WHERE id = 1013638;\n\nselect * from teams where id = 90;\nselect * from users where team_id = 90;\nselect * from social_accounts where social_accounts.sociable_id IN (1960,1760);\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 71;\nselect * from invitations where team_id = 90;\n\nselect * from crm_configurations where id = 71;\nselect * from accounts where crm_configuration_id = 71 order by id desc;\nselect * from leads where crm_configuration_id = 71 order by id desc;\nselect * from contacts where crm_configuration_id = 71 order by id desc;\nselect * from opportunities where crm_configuration_id = 71 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 71 order by id desc;\nselect * from crm_fields where crm_configuration_id = 71 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 71 order by id desc;\nselect * from stages where crm_configuration_id = 71 order by id desc;\n\nselect * from users order by secondary_email desc;\nselect u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa\n join users u on sa.sociable_id = u.id\nwhere sa.provider = 'google' and u.email LIKE 'aneliya%';\n\nselect * from failed_jobs order by id desc;\n\nselect * from users where email = 'ben.allwright@learningpeople.co.uk' or secondary_email = 'ben.allwright@learningpeople.co.uk';\n\nselect * from teams;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 39;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\n# ************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;\nSELECT * FROM crm_configurations WHERE id = 70;\n\nselect * from teams where id = 1;\nselect * from groups where team_id = 1;\nselect * from users where team_id = 1;\n\nselect o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o\njoin users u on o.user_id = u.id\njoin groups g on u.group_id = g.id\njoin role_user ru on u.id = ru.user_id\njoin roles r on ru.role_id = r.id\nwhere o.crm_configuration_id = 39 and close_date > '2024-01-01 00:00:00';\n\nselect * from role_user where user_id = 143;\nselect * from roles;\n\nselect * from role_user;\nselect * from groups where id = 9;\nselect * from scope_groups where group_id = 9;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations;\nSELECT * FROM social_accounts WHERE sociable_id = 121;\n\nhttps://crmsandbox.zoho.com/crm/jiminnyw4/tab/Leads/4776201000005049105\nhttps://crmsandbox.zoho.com/crm/\n\nhttps://crm.zoho.com/crm/org3469620/tab/Leads/230045000229559080\n https://crm.zoho.com/crm/\n org3469620\n\nSELECT * FROM activities WHERE uuid_to_bin('03382d20-c8bc-48e7-a3d4-90b52fa5ceab') = uuid;\n\nselect * from users where email LIKE \"%mobile_automation_%\";\nselect * from social_accounts where sociable_id IN (2228);\nselect * from crm_profiles where user_id IN (2222,2223,2226,2227);\n\nselect * from teams order by id desc;\nSELECT * FROM users WHERE id = 2229;\nSELECT * FROM crm_profiles WHERE user_id = 2229;\nselect * from opportunities where crm_configuration_id = 88;\nselect * from crm_fields where crm_configuration_id = 88;\nselect * from crm_profiles where crm_configuration_id = 88;\n\nSELECT * FROM teams WHERE id = 1;\n\nSELECT * FROM users WHERE id = 143;\nSELECT * FROM users WHERE uuid_to_bin('fde193d3-06a2-4e1a-8895-62b94039215d') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73385071-a756-42ae-9c73-8b53f2309467') = uuid;\n\nhttps://app.staging.jiminny.com/ondemand?\n min_duration=1\n &\n only_recorded=1\n &\n user_id%5B%5D=641f1acb-16b8-42d1-8726-df52979dad0e\n &\n sequence_number=2\n\n select * from users where team_id = 1 and email like '%stoyan%'\n\nselect * from coaching_feedbacks;\n\nselect * from teams;\nSELECT * FROM users WHERE team_id = 36;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from users where id = 143;\n\nSELECT * FROM users WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM activity_shares WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\n\nselect * from users where team_id = 2;\nselect * from activities where crm_configuration_id = 39\nand activities.scheduled_start_time BETWEEN '2025-04-09 00:00:00' AND '2025-04-09 23:59:59'\nAND user_id = 143\norder by id desc;\n\n# ************************************************************************************\nselect * from teams where id = 142; # 2312, 126\nselect * from team_settings;\nselect * from users where team_id = 142; # 21642\nSELECT * FROM social_accounts WHERE sociable_id = 21642;\nSELECT * FROM crm_profiles cp join users u ON u.id = cp.user_id WHERE team_id = 142;\nselect * from crm_profiles where id IN (93);\nselect * from invitations;\nselect * from team_features where team_id = 1;\n\nSELECT * FROM crm_configurations WHERE id = 126;\nselect * from accounts where crm_configuration_id = 126 order by id desc;\nselect * from leads where crm_configuration_id = 126 order by id desc;\nselect * from contacts where crm_configuration_id = 126 order by id desc;\nselect * from opportunities where crm_configuration_id = 126 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 126 order by id desc;\nselect * from crm_fields where crm_configuration_id = 126 # 11060\n# and type IN ('picklist', 'status')\n# and object_type = 'task'\norder by id desc;\n# 5731,5732,5733\nselect DISTINCT crm_field_id from crm_field_values where crm_field_id IN (11151,12239,12215,12185,12175,12165,12144,12137,12127,12109,12107,12105,12103,12092,12037,12005,12003,11987,11969,11958,11951,11942,11931,11924,11921,11917,11915,11901,11893,11883,11872,11870,11868,11866,11839,11833,11821,11793,11780,11777,11769,11757,11737,11735,11656,11645,11638,11629,11618,11611,11602,11591,11584,11581,11558,11544,11543,11534,11532,11529,11527,11503,11497,11493,11488,11470,11468,11457,11455,11397,11387,11372,11363,11348,11323,11318,11309,11301,11300,11292,11290,11286,11284,11256,11252,11242,11237,11233,11219,11176,11160) order by id desc;\nselect * from crm_layouts where crm_configuration_id = 126 order by id desc;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id in (300,299,298);\nselect * from stages where crm_configuration_id = 126 order by id desc;\nselect * from business_processes where crm_configuration_id = 126 order by id desc;\nselect * from business_process_stages where business_process_id IN (76,75,74,73);\nselect * from playbooks where team_id = 142;\nselect * from playbook_layouts where playbook_id IN (108);\nSELECT * FROM playbook_categories WHERE playbook_id IN (108);\n\nselect * from teams where id = 130;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 2\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities\n WHERE crm_configuration_id = 110;\n\nselect * from teams;\nselect * from crm_configurations;\n\nSELECT * FROM activities WHERE id = 628773;\nSELECT * FROM crm_profiles WHERE user_id = 1460;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from teams;\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from teams where id = 145;\nselect * from crm_configurations where id = 129;\nselect * from social_accounts where sociable_id = 2317;\nSELECT * FROM activities WHERE uuid_to_bin('8dbab184-a333-4268-ad57-fb41f8d53a9a') = uuid;\n\nselect * from teams where id = 1;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 280;\nSELECT * FROM crm_layout_entities WHERE id = 5507;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type IN ('event');\n\nselect * from teams;\nselect * from activities where crm_configuration_id = 14;\n\nSELECT * FROM social_accounts where provider = 'copper';\n\nselect * from activities where id = 628467;\nselect * from participants where activity_id = 628467;\n\nSELECT * FROM contacts WHERE id = 3969;\nSELECT * FROM accounts WHERE id = 177;\n\nSELECT * FROM activities WHERE uuid_to_bin('4eb54c77-cfa3-2bd4-84a7-9ed46a21c988') = uuid;\n\n# ********************* BH\nselect * from teams where id = 36;\nSELECT * FROM crm_configurations WHERE id = 21;\nselect * from activities where crm_configuration_id = 21 and id = 607901;\nselect * from activities where crm_configuration_id = 21;\n\nselect * roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 226;\n\nselect * from migrations order by id desc;\n\n# mercury\n# neptune\n# earth\n\nselect * from teams;\nselect * from teams where id = 19;\nselect * from teams where id = 27;\nselect * from users where team_id = 27;\nSELECT * FROM crm_configurations WHERE id = 42;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from activities where id = 631461;\nSELECT * FROM crm_field_values WHERE crm_field_id = 180;\n\nselect * from teams where id = 2;\nSELECT * FROM social_accounts WHERE sociable_id = 89;\n\nSELECT * FROM activities WHERE uuid_to_bin('ba0c029a-bc14-4e17-8603-64174acebcbb') = uuid; # 634273\nselect * from activity_summary_logs where activity_id = 634273;\n\nselect * from sidekick_settings where team_id = 2;\n\nselect * from teams; # 2, 2\nSELECT * FROM crm_configurations WHERE team_id = 2; # 2\nselect * from team_features where team_id = 2;\nselect * from features;\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 and crm_provider_id = '51317301383';\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 order by id desc;\n\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from users where team_id = 1 and id IN (7160, 3248);\nselect * from migrations order by id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nselect * from teams where id = 1;\nselect * from groups g JOIN playbooks p on g.playbook_id = p.id where g.team_id = 1;\nselect * from groups where id = 565;\nselect * from playbooks where team_id = 1;\nselect * from playbooks where id = 175;\nselect * from playbook_categories where playbook_id = 175;\nselect * from users where team_id = 1052;\nselect * from users where id = 7160;\nselect * from crm_profiles where user_id = 7160;\nselect * from features;\nselect\n *\n# id, uuid, type, provider, playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id, stage_id,\n# crm_configuration_id, crm_provider_id, transcription_id, status\nfrom activities where crm_configuration_id = 1 and type = 'conference'\n# and crm_provider_id IS NOT NULL\nand provider != 'uploader' and actual_start_time IS NOT NULL\nORDER by id desc;\nselect * from activities where id = 54747783; # 00UO400000pCzojMAC\n\nselect p.id, p.activity_type, pc.id, pc.name\nFROM playbooks p\njoin playbook_categories pc on p.id = pc.playbook_id\nwhere p.team_id = 1 and p.activity_type = 'event';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 1 and object_type = 'event';\nSELECT * FROM crm_field_values WHERE crm_field_id = 4;\n\nselect * from crm_layouts cl join playbook_layouts pl on cl.id = pl.layout_id\nwhere crm_configuration_id = 1 and pl.playbook_id = 175;\n\nselect * from teams;\nSELECT r.* FROM automated_reports r\njoin teams t on r.team_id = t.id\nWHERE r.frequency = 'daily'\n and r.status = 1\nAND t.status = 'active'\nAND (r.expires_at >= now() OR r.expires_at IS NULL);\n\nselect * from automated_report_results where report_id IN (18, 33);\n\nselect * from users where team_id = 1 and id = 1047;\nSELECT * FROM social_accounts WHERE sociable_id = 1047;\n\nselect * from activity_searches where id = 10932;\nselect * from activity_search_filters where activity_search_id = 10932;\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from automated_reports where id IN (55);\nselect * from automated_report_results where id IN (81);\nselect * from users where id IN (10633, 13987, 11985);\nselect * from users where group_id IN (3710);\n\nSELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;\n\nselect * from teams;\nselect * from accounts where team_id = 1;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('82e74956-6144-4cd1-a3d3-af985c3070a4') = uuid;\n\nselect * from teams where id = 1029;\nselect * from crm_configurations where provider = 'pipedrive';\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 = 1029 and sa.provider = 'pipedrive';\n\n[\n {\n \"user_id\": \"23460 (owner)\",\n \"email\": \"integration-account@pipedrive.jiminny.com\",\n \"id\": 69,\n \"sociable_id\": 23460,\n \"provider_user_id\": \"19555731\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:rYyABXmXsBhEdYU_dfmDH8GF-vzSseJXE5bds_zAyVdAwlTXOPdTl9i4PS4jVofLvpq7IRgvEt2BzGhR6cWiQXHHD0AtayQOkZm262ClFCsMYtKGfep0Jq1n0eiRIVqT9gAY7rWvhpEDF8oAlgnRGmqx-euIkpzE79sPXh4OjNx_yUIaanjyplGpBBJ_NiACd1sMlZmseyUyyU_gldqlCBAuK9hhATc9icgg7zuoc7nKBBrlg49tRtzEagDh6xbFBpzfCp7kE_7n4TLWfWHLPMzu-bktjwA969G9sFRmoH1GjPA0a2odDT4dk1_1ouBrB1NcTT2hQUqH-_RzDW2nWmeoVHA\",\n \"provider_refresh_token\": \"5034113:19555731:87c14258f0c813d02767ee975f6044d46b6b2bfc\",\n \"expires\": 1779091997,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"connected\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 08:23:28\",\n \"updated_at\": \"2026-05-18 07:13:18\",\n \"provider_user_token_encrypted\": \"eyJpdiI6Ik9oYzBwcTVteWN4ajBRaDdMb0FjWGc9PSIsInZhbHVlIjoiQUNMbjU5UHR2Q1RnbWRXMEU1TUx6UVpRU3gzdVc5WktmTE4rVlhXa3lRaGhyUUlZMVZRWEJuR0JaWWhZZXNPRlBuanhuYU5MVHZ5TG9NTVVjNjJSUUpZZ2VhbGYxbHg0UzJEdTVmQjNFZnJRZkMwYjd0N2RMZ05GRS9IR3c2K0NoVjBjYTA5UG12SkxHeDlDMGVNN3ptUWUzblFiTngyYzR1eUpHSEYrdEwvZm0yZklGYjBSNEtTR2ZGazhLM1hqT3lVbjFobDNPZ0d3anFlcjhKcXpERlZGOVN1YmFyNDIvM1BFRDFMYnp4WEI4TGVLM2xYcy9CL0RDOWlQNHI3N0NwWnJPMWRtZllmM2ZKeE9TV2NBeDZxL2M1YnlSVzd3ZW96T3F1QmtBYXBHYkUraGcvdCtRajlYZXBjVVBSdFlMUjVPVDVJbDdyenVoWjMrbVJvU3ZZR1dQZ3pqQ3F3aDF2U2xPZWZIN3BCWVFLNXpxQUtDb2pIK0xHc1E3SklSM3Q0VkNSbm9oK2pFK3hLaW54T1dWbEVneUp0RGhhdVBuOFI4MXROc3dZWnFnTUpiaDVMMnZ4QmlRM3k4QWFlMVFWUFYvdGhJQzZBYnhBQmhWa2ZKN1ZhSnhpaExxbmlTemgzUWw3aXJtWjlSMlhmd0lWMDNDN1N3My9Ua0hCL2xqY3RkVFhMSjFJMDRjOE5DWlgrZ3FMVXN6RWlwUE5GWERZdG1xVjVxOFlLRGs2VVJKS3FLeWRxQjYxdDh4Z2JJNXhlWEZ3dkQ4SGtybDNUcndzblFHeVJNRkYraFh2UDFIUTdMQ1BZa3dEU1dBbzk5K0dyT2RNVFBZZUJpRytSck5pYlI1YUZyMmhUNEZCdWxHYmJLREtzbUpjVkhvV0RoejJpbm1SWHlNaXE5M0RhcS94UW9EdFoweWF3bVFVY0dTZWFPSXBmOCtDYndia215cmtyZU1oT0Exam1CV2tPblNhYjY4clVEeUs3anVHUmNHeS9YLzRha1VhbGl3N3lwaDlzZnRhQUZta2s4eFllNHgzRklSRmNyazJ4dlBDMnByNCtBRjNaVjJCTT0iLCJtYWMiOiJkYTQxZDY1OTY2ZTljMTgyZWRhNGEzMGZjZDc2MjBjN2NlNzU2YTViNGQxNWE1NTI2ZmI1MWQyYjQ2ODYxZmEwIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6Imt2bGxlSmxUK05GMjF0dEtPaTMrUlE9PSIsInZhbHVlIjoiUXZHTElZRXkreHFxUU02SnZ4eVBacG9WWTRlVkd0USszV3JyVFlpU2ZaY25GSWo2WFcrRzNlbFRlUXRQczNwSXRCcEdvZEpveG9jMzBDSTgwdnZLQnc9PSIsIm1hYyI6ImQxYWI0NzU5Nzg5MDI4YWVhZmQ4Mjg1YzhkZDQzMjRkYWYwYTdhZTY5MDMxMjc0OWNiYjY0Nzc3NDQ0MTEyY2EiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300786192D9D96DD60D3D1EBC9DFAEE5F0C45EE80165CF3F3D2B3B627026AA7CFC7CA0128DD463535D32EE491ADBADF8B07596B0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040C7FB1319048ECB2EA3F23B995020110802B52D22F5EAD341AB238FBBCB6093156E443876A664BA5555D722565C2B2D04422C868CD7350555E3CC74221\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n },\n {\n \"user_id\": \"23463\",\n \"email\": \"jiminny_web_sa@pipedrive.jiminny.com\",\n \"id\": 72,\n \"sociable_id\": 23463,\n \"provider_user_id\": \"23270841\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:txqCuWLeVhgwiaFqXIvQWWrtrnFIy_4lT3VCr-sRB4g6_2lK8KcQ_6ka_qFmZhr-IeIAKmAImx6H1iIKx4Ab7XZ5MnKIh03GKbHjI0n0rGT9UYkeH21jKOxJvKaSX_TyLbxFPR6irPQyvqcpBClXI52gVJH01KzZy_dMTHFXhhDLOIhEpSrQXHG7Qo8q7OuBeSPZrU1ALi9kmAm4GTpzGTbzfl-hUt9IAfPunJOCyv3mf2Tl-MT8EyQgOFPrsP3yz9UlSyVhb40zO_bCnUrqNxjwgm_E6vgpVrwULTQbHe-43Dq-TRetjceUzT88GBgVJ0UdxXP5BRBVXcL5ir8-9ZTMaNU\",\n \"provider_refresh_token\": \"5034113:23270841:34790b44838f5fd422c2d2c82e00f1ecf2178ad1\",\n \"expires\": 1753837219,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"full-refresh\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 10:41:12\",\n \"updated_at\": \"2025-07-30 01:00:17\",\n \"provider_user_token_encrypted\": \"eyJpdiI6InVEVEl2SzIxMjd1bkNDWG9lY3YvQ0E9PSIsInZhbHVlIjoiRlJLbDZ3ZHo2dHMxUWQwdGU2YUZjV3lPWHlxQTJ0eWh4S0RTMjlSaThVcktoaWhXcTd2UXl4Mjg4bW5UUnZCZEQ5NXpuQTVKOURiMDNIa3l3K0lSWCt5azRBOEdHbitWQXhxeEpMVUZ1dnF2NVl1TTZLelZOaGNvRlBLeGpIWlpoRGloUEprd2xoNUFPcTlLcUd3WVlUU2svR1NOeXBYQ2NnMWhnK1V2aytOeVVMNzJGdVZXMU1JS3BSaGNCcmxkVjEwQ01mQXNBdWNhS1lMZWZobnZwcHBkN1R4bUVDRUNYdnNtSVJkdG5MdkN3djJBT0hMRDl1MHFGbnl4WU13ejBkUWsrdUljWkZhcTJlN0JDSGdTVzlPY0FGMUJlZi9WRGpkMUk5R20wblYwSk9VR2FuaHpLTzJNeitMbnF1V1NEMUUxRmYzaDRGZDMyaXd3Z0FjQno4SzVoYjUyTmV3UXNpRlF4TGZKNVl3dUFqdGhKVWJjRVlUUXRGalBpaXJvSGJmbS8rd25aQ2Zvc05saHRDRjlHV1VEUFFiRU5xbWRVNkxFSXV0RUZyaUlYNWMwMmhnZ0Y1VUQ4eEFkY2QyWXpnR0NidkVJSWdjVGljUjA3NDdpZW9WUHhtSlpGSGdNU2hRUTA5ZW03RGpiRFdrdytkOHJXSUxlazZNaG9iaUg2NFZYdEc3YklMeFZvblBzWmVRSDcvN2M4WUNtL3h4S2IrUW00cXhialBia3BJcW5XallBNlV5WWdhcE1ZVFBBM3RSSUVBamYvOGZEQWM5a2FJMGwyWkRSU3dlTEtPemZlQ3RXRGNDcEdYRHdMNTlTQVg2SUdUN0hVaXdZT1dUOUlrVzkrZHFBemhwWXg1cm4rSy9UOHUzcnNSM2dISlhBRTEyVUNyTkZYaFJYUlN1a2RKVHhhM2dHckR3a1JGaVZ2Wk9BVnhTclVpSEhwWTVpQTlJbXVkOUxSTGpRbDk0a1VtbE9QMVAvN3VlVEhJUHd2elowd0laNVIzZ3M3N0ZOK0NDakIwQ2FicGxoMDBhTXI0VUppUmFOZHdlWUdGV21NNFQ4RU1nY0dnWT0iLCJtYWMiOiI0ZTU4ZmJkNTdkYmY0NGE4NTJjZjlhNDExNzE2YjhlOWM2NTA5OGY2MDA4OTcyZDVlOTljY2JjZDhmMjBhMDUyIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6IkJGMkdRVHRKM2VTcitKNGcvQWJtUGc9PSIsInZhbHVlIjoicmFyRkxPZ1Rybm1ORXlEVjJ2TXFGTzJtM3hWaFhnUVVHN2ZlR1lRM0I5d3ozbnZTcU5EdzJqRkI2elhyNWhlenRTUXV3bjk0N1JXeklDMVAyUzBKcHc9PSIsIm1hYyI6ImJhODVjMGQyZDE3Y2ExNjc2OWVjYWJiNmFjYWVkODIyMTMyNWVhYTExMTgwYTEyMTU0MzUzZGE1YjQ5YzQ5ZjEiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300788C37CDF66ABE9301A68D5D4866AC0C197E04EEE4D904F20A59991322EBAE252301BEF4B24FF01359E934E5654617E4EEAC0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040CEB00EF45BDEA999A5558889E020110802B925F372F7BEFAF0B45E48686113D1DA430ECFCC07B1F61BA6828CC44235278EDB05C486E8068D0BE737D91\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n }\n]","depth":4,"on_screen":true,"value":"SELECT * FROM teams WHERE id = 1;\n\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;\nSELECT * FROM crm_fields WHERE id = 2234;\nSELECT * FROM crm_field_values WHERE crm_field_id = 2234;\n\nselect * from crm_profiles where user_id = 143;\n\nselect * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO\nselect * from business_processes where crm_configuration_id = 39;\n# 01941000000H669AAC, 01941000000H66JAAS\n\nselect * from record_type_field_values\n where record_type_id IN (24);\n\nselect * from crm_field_values where id IN (2730);\n\nselect * from crm_configurations where id = 39;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce'; #1035\n\n\nselect * from users where team_id = 1; # 222 group 3\nSELECT * FROM activities WHERE user_id = 222 order by id desc;\nselect * from sidekick_settings where team_id = 1;\nselect * from teams where id = 1;\nselect * from team_features where team_id = 1;\n\nselect * from activities where crm_configuration_id = 2\nand provider = 'ms-teams' and id = 608765;\n\nSELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';\n\nselect * from sidekick_settings where team_id = 2;\n\nSELECT * FROM activities WHERE id = 608660;\nselect * from activity_summary_logs where activity_id = 608660;\nselect * from ai_prompts where transcription_id = 11214;\n\n# ********************************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;\n# id: 608818, crm: 59628809737\nSELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;\n# id: 608821, crm: 59632069252\nSELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,\nplaybook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,\nscheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at\nFROM activities a\njoin calendar_events ce on a.calendar_event_id = ce.id\nWHERE a.id IN (608818, 608821);\n\nselect * from users where team_id = 1;\nselect * from team_settings where team_id = 1;\nselect * from crm_profiles where crm_configuration_id = 39 order by user_id;\n\nselect * from team_features where team_id = 1;\n\nselect * from users where team_id = 2;\n\nSELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639\n# Preslava N. Ivanova, grou id 3\n\nSELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;\n\nselect * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';\n\nselect\n a.id,\n a.type,\n a.scheduled_start_time,\n a.actual_start_time,\n a.created_at,\n a.opportunity_id,\n a.status\nFROM activities a\nWHERE opportunity_id = 344\nand status IN ('completed', 'received', 'delivered')\nand (\n (a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')\nOR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))\n;\n\nSELECT * FROM users WHERE id = 222;\n\nSELECT * FROM crm_profiles WHERE user_id = 222;\nselect * from crm_layouts where crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;\n\nselect * from group_deal_risk_types;\n\nselect * from opportunities where team_id = 1;\n\nSELECT * FROM opportunities WHERE id = 315;\nSELECT * FROM crm_field_data WHERE object_id = 315;\nselect * from crm_field_data where object_id = 260;\n\nselect * from generic_ai_prompts where subject_id = 315;\n\nselect * from teams; # 36, 21, 121, james.graham@bullhorn.jiminny.com\nSELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';\n\n# ************************************************************************************\nselect * from teams where id = 1;\nselect * from crm_configurations where id = 39;\nselect * from users where team_id = 1;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 1;\n# 1 - 00541000004281rAAA\n# 204 - 0052g000003freeAAA\n# 429 - 0052g000003qGOiAAM\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\nselect * from activities where type = 'softphone'\nand created_at > '2024-12-11 15:24:36' order by id desc;\n\nselect * from activity_providers where team_id = 1;\nselect * from activity_provider_users where activity_provider_id = 328;\n\nselect * from opportunities where crm_configuration_id = 39\nAND account_id = 178 AND is_closed = false\norder by created_at DESC;\n\nselect * from contacts where id = 3952;\nselect * from accounts where id = 178;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations where id = 21;\nselect * from users where team_id = 36;\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 36;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 36\nand sa.provider = 'bullhorn';\n\nselect * from social_accounts where id = 348;\nUPDATE social_accounts SET\nprovider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',\nprovider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',\nexpires = 1733998131,\nstate = 'connected'\nWHERE id = 348;\n\n# ************************************************************************************\nselect * from teams where id = 31;\nselect * from crm_configurations where id = 18;\n\nselect * from users where team_id = 31; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 31;\n\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 31\nand sa.provider = 'close';\n\nselect * from contacts where crm_configuration_id = 18;\n\n# ********************** NEPTUNE **************************************************************\nselect * from teams;\nselect * from users where id IN (1030, 1035, 1052);\nselect * from crm_configurations;\n\nselect * from users where team_id = 65; # 257\nselect * from team_settings where team_id = 65; # 257\nselect * from invitations where team_id = 65; # 257\nselect * from users where email = 'integration-account@jiminny.com'; # 257\nselect u.email, cp.* from users u\njoin crm_profiles cp on u.id = cp.user_id\nwhere u.team_id = 65;\n\nselect * from crm_configurations where id = 53;\nselect * from accounts where crm_configuration_id = 53 order by id desc;\nselect * from leads where crm_configuration_id = 53 order by id desc;\nselect * from contacts where crm_configuration_id = 53 order by id desc;\nselect * from opportunities where crm_configuration_id = 53 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 53 order by id desc;\nselect * from crm_fields where crm_configuration_id = 53 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 53 order by id desc;\nselect * from stages where crm_configuration_id = 53 order by id desc;\n\n\nselect * from crm_profiles where crm_configuration_id = 13;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\nand sa.provider = 'integration-app';\n\nselect * from contacts where crm_configuration_id = 13;\n\nselect * from social_accounts where sociable_id = 283;\n\nSELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';\n\nselect * from activity_providers where team_id = 65;\nSELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 65\n;\n\n# ***************************** STAGING ********************************************\nSELECT * FROM teams;\nSELECT * FROM teams WHERE id = 88;\nSELECT * FROM teams WHERE id = 89;\nselect * from team_settings where team_id = 89;\nSELECT * FROM users WHERE team_id = 89;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 89;\n\nselect * from users;\nSELECT * FROM social_accounts WHERE sociable_id = 1761;\nSELECT * FROM crm_configurations WHERE id = 70;\nselect * from accounts where crm_configuration_id = 70 order by id desc;\nselect * from leads where crm_configuration_id = 70 order by id desc;\nselect * from contacts where crm_configuration_id = 70 order by id desc;\nselect * from opportunities where crm_configuration_id = 70 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 70 order by id desc;\nselect * from crm_fields where crm_configuration_id = 70 order by id desc;\nselect * from crm_field_values where crm_field_id = 3536 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 70 order by id desc;\nselect * from stages where crm_configuration_id = 70 order by id desc;\nselect * from business_processes where crm_configuration_id = 70 order by id desc;\nselect * from business_process_stages where business_process_id = 34;\n\nselect * from contacts where id = 10468;\n\nselect * from crm_layouts where crm_configuration_id = 70;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;\nSELECT * FROM crm_fields WHERE id IN (3533,3534,3535);\n\nselect * from activities where crm_configuration_id = 70\nand (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;\n\nSELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;\nSELECT * FROM activities where crm_configuration_id = 69 ;\n\nSELECT * FROM users WHERE email LIKE '%jiminny_web_sa2@jiminny.com%';\nSELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;\nSELECT * FROM opportunities WHERE id = 385;\n\nselect * from participants p\njoin activities a on p.activity_id = a.id\nwhere a.crm_configuration_id = 70\nand (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);\nSELECT * FROM participants WHERE id = 1013638;\n\nselect * from teams where id = 90;\nselect * from users where team_id = 90;\nselect * from social_accounts where social_accounts.sociable_id IN (1960,1760);\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 71;\nselect * from invitations where team_id = 90;\n\nselect * from crm_configurations where id = 71;\nselect * from accounts where crm_configuration_id = 71 order by id desc;\nselect * from leads where crm_configuration_id = 71 order by id desc;\nselect * from contacts where crm_configuration_id = 71 order by id desc;\nselect * from opportunities where crm_configuration_id = 71 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 71 order by id desc;\nselect * from crm_fields where crm_configuration_id = 71 order by id desc;\nselect * from crm_field_values where crm_field_id = 3341 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 71 order by id desc;\nselect * from stages where crm_configuration_id = 71 order by id desc;\n\nselect * from users order by secondary_email desc;\nselect u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa\n join users u on sa.sociable_id = u.id\nwhere sa.provider = 'google' and u.email LIKE 'aneliya%';\n\nselect * from failed_jobs order by id desc;\n\nselect * from users where email = 'ben.allwright@learningpeople.co.uk' or secondary_email = 'ben.allwright@learningpeople.co.uk';\n\nselect * from teams;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 39;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 1\nand sa.provider = 'salesforce';\n\n# ************************************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;\nSELECT * FROM crm_configurations WHERE id = 70;\n\nselect * from teams where id = 1;\nselect * from groups where team_id = 1;\nselect * from users where team_id = 1;\n\nselect o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o\njoin users u on o.user_id = u.id\njoin groups g on u.group_id = g.id\njoin role_user ru on u.id = ru.user_id\njoin roles r on ru.role_id = r.id\nwhere o.crm_configuration_id = 39 and close_date > '2024-01-01 00:00:00';\n\nselect * from role_user where user_id = 143;\nselect * from roles;\n\nselect * from role_user;\nselect * from groups where id = 9;\nselect * from scope_groups where group_id = 9;\n\n# ************************************************************************************\nselect * from teams where id = 36;\nselect * from crm_configurations;\nSELECT * FROM social_accounts WHERE sociable_id = 121;\n\nhttps://crmsandbox.zoho.com/crm/jiminnyw4/tab/Leads/4776201000005049105\nhttps://crmsandbox.zoho.com/crm/\n\nhttps://crm.zoho.com/crm/org3469620/tab/Leads/230045000229559080\n https://crm.zoho.com/crm/\n org3469620\n\nSELECT * FROM activities WHERE uuid_to_bin('03382d20-c8bc-48e7-a3d4-90b52fa5ceab') = uuid;\n\nselect * from users where email LIKE \"%mobile_automation_%\";\nselect * from social_accounts where sociable_id IN (2228);\nselect * from crm_profiles where user_id IN (2222,2223,2226,2227);\n\nselect * from teams order by id desc;\nSELECT * FROM users WHERE id = 2229;\nSELECT * FROM crm_profiles WHERE user_id = 2229;\nselect * from opportunities where crm_configuration_id = 88;\nselect * from crm_fields where crm_configuration_id = 88;\nselect * from crm_profiles where crm_configuration_id = 88;\n\nSELECT * FROM teams WHERE id = 1;\n\nSELECT * FROM users WHERE id = 143;\nSELECT * FROM users WHERE uuid_to_bin('fde193d3-06a2-4e1a-8895-62b94039215d') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73385071-a756-42ae-9c73-8b53f2309467') = uuid;\n\nhttps://app.staging.jiminny.com/ondemand?\n min_duration=1\n &\n only_recorded=1\n &\n user_id%5B%5D=641f1acb-16b8-42d1-8726-df52979dad0e\n &\n sequence_number=2\n\n select * from users where team_id = 1 and email like '%stoyan%'\n\nselect * from coaching_feedbacks;\n\nselect * from teams;\nSELECT * FROM users WHERE team_id = 36;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from users where id = 143;\n\nSELECT * FROM users WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM teams WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\nSELECT * FROM activity_shares WHERE uuid_to_bin('73180eeb-33de-4065-977d-ccbe0e6c94fc') = uuid;\n\nselect * from users where team_id = 2;\nselect * from activities where crm_configuration_id = 39\nand activities.scheduled_start_time BETWEEN '2025-04-09 00:00:00' AND '2025-04-09 23:59:59'\nAND user_id = 143\norder by id desc;\n\n# ************************************************************************************\nselect * from teams where id = 142; # 2312, 126\nselect * from team_settings;\nselect * from users where team_id = 142; # 21642\nSELECT * FROM social_accounts WHERE sociable_id = 21642;\nSELECT * FROM crm_profiles cp join users u ON u.id = cp.user_id WHERE team_id = 142;\nselect * from crm_profiles where id IN (93);\nselect * from invitations;\nselect * from team_features where team_id = 1;\n\nSELECT * FROM crm_configurations WHERE id = 126;\nselect * from accounts where crm_configuration_id = 126 order by id desc;\nselect * from leads where crm_configuration_id = 126 order by id desc;\nselect * from contacts where crm_configuration_id = 126 order by id desc;\nselect * from opportunities where crm_configuration_id = 126 order by id desc;\nselect * from crm_profiles where crm_configuration_id = 126 order by id desc;\nselect * from crm_fields where crm_configuration_id = 126 # 11060\n# and type IN ('picklist', 'status')\n# and object_type = 'task'\norder by id desc;\n# 5731,5732,5733\nselect DISTINCT crm_field_id from crm_field_values where crm_field_id IN (11151,12239,12215,12185,12175,12165,12144,12137,12127,12109,12107,12105,12103,12092,12037,12005,12003,11987,11969,11958,11951,11942,11931,11924,11921,11917,11915,11901,11893,11883,11872,11870,11868,11866,11839,11833,11821,11793,11780,11777,11769,11757,11737,11735,11656,11645,11638,11629,11618,11611,11602,11591,11584,11581,11558,11544,11543,11534,11532,11529,11527,11503,11497,11493,11488,11470,11468,11457,11455,11397,11387,11372,11363,11348,11323,11318,11309,11301,11300,11292,11290,11286,11284,11256,11252,11242,11237,11233,11219,11176,11160) order by id desc;\nselect * from crm_layouts where crm_configuration_id = 126 order by id desc;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id in (300,299,298);\nselect * from stages where crm_configuration_id = 126 order by id desc;\nselect * from business_processes where crm_configuration_id = 126 order by id desc;\nselect * from business_process_stages where business_process_id IN (76,75,74,73);\nselect * from playbooks where team_id = 142;\nselect * from playbook_layouts where playbook_id IN (108);\nSELECT * FROM playbook_categories WHERE playbook_id IN (108);\n\nselect * from teams where id = 130;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 2\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities\n WHERE crm_configuration_id = 110;\n\nselect * from teams;\nselect * from crm_configurations;\n\nSELECT * FROM activities WHERE id = 628773;\nSELECT * FROM crm_profiles WHERE user_id = 1460;\nSELECT * FROM social_accounts WHERE sociable_id = 2291;\n\nselect * from teams;\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from teams where id = 145;\nselect * from crm_configurations where id = 129;\nselect * from social_accounts where sociable_id = 2317;\nSELECT * FROM activities WHERE uuid_to_bin('8dbab184-a333-4268-ad57-fb41f8d53a9a') = uuid;\n\nselect * from teams where id = 1;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 39;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 280;\nSELECT * FROM crm_layout_entities WHERE id = 5507;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type IN ('event');\n\nselect * from teams;\nselect * from activities where crm_configuration_id = 14;\n\nSELECT * FROM social_accounts where provider = 'copper';\n\nselect * from activities where id = 628467;\nselect * from participants where activity_id = 628467;\n\nSELECT * FROM contacts WHERE id = 3969;\nSELECT * FROM accounts WHERE id = 177;\n\nSELECT * FROM activities WHERE uuid_to_bin('4eb54c77-cfa3-2bd4-84a7-9ed46a21c988') = uuid;\n\n# ********************* BH\nselect * from teams where id = 36;\nSELECT * FROM crm_configurations WHERE id = 21;\nselect * from activities where crm_configuration_id = 21 and id = 607901;\nselect * from activities where crm_configuration_id = 21;\n\nselect * roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 226;\n\nselect * from migrations order by id desc;\n\n# mercury\n# neptune\n# earth\n\nselect * from teams;\nselect * from teams where id = 19;\nselect * from teams where id = 27;\nselect * from users where team_id = 27;\nSELECT * FROM crm_configurations WHERE id = 42;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 19\nand sa.provider = 'pipedrive';\n\nselect * from activities where id = 631461;\nSELECT * FROM crm_field_values WHERE crm_field_id = 180;\n\nselect * from teams where id = 2;\nSELECT * FROM social_accounts WHERE sociable_id = 89;\n\nSELECT * FROM activities WHERE uuid_to_bin('ba0c029a-bc14-4e17-8603-64174acebcbb') = uuid; # 634273\nselect * from activity_summary_logs where activity_id = 634273;\n\nselect * from sidekick_settings where team_id = 2;\n\nselect * from teams; # 2, 2\nSELECT * FROM crm_configurations WHERE team_id = 2; # 2\nselect * from team_features where team_id = 2;\nselect * from features;\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 and crm_provider_id = '51317301383';\nSELECT * FROM opportunities WHERE crm_configuration_id = 2 order by id desc;\n\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from users where team_id = 1 and id IN (7160, 3248);\nselect * from migrations order by id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nselect * from teams where id = 1;\nselect * from groups g JOIN playbooks p on g.playbook_id = p.id where g.team_id = 1;\nselect * from groups where id = 565;\nselect * from playbooks where team_id = 1;\nselect * from playbooks where id = 175;\nselect * from playbook_categories where playbook_id = 175;\nselect * from users where team_id = 1052;\nselect * from users where id = 7160;\nselect * from crm_profiles where user_id = 7160;\nselect * from features;\nselect\n *\n# id, uuid, type, provider, playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id, stage_id,\n# crm_configuration_id, crm_provider_id, transcription_id, status\nfrom activities where crm_configuration_id = 1 and type = 'conference'\n# and crm_provider_id IS NOT NULL\nand provider != 'uploader' and actual_start_time IS NOT NULL\nORDER by id desc;\nselect * from activities where id = 54747783; # 00UO400000pCzojMAC\n\nselect p.id, p.activity_type, pc.id, pc.name\nFROM playbooks p\njoin playbook_categories pc on p.id = pc.playbook_id\nwhere p.team_id = 1 and p.activity_type = 'event';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 1 and object_type = 'event';\nSELECT * FROM crm_field_values WHERE crm_field_id = 4;\n\nselect * from crm_layouts cl join playbook_layouts pl on cl.id = pl.layout_id\nwhere crm_configuration_id = 1 and pl.playbook_id = 175;\n\nselect * from teams;\nSELECT r.* FROM automated_reports r\njoin teams t on r.team_id = t.id\nWHERE r.frequency = 'daily'\n and r.status = 1\nAND t.status = 'active'\nAND (r.expires_at >= now() OR r.expires_at IS NULL);\n\nselect * from automated_report_results where report_id IN (18, 33);\n\nselect * from users where team_id = 1 and id = 1047;\nSELECT * FROM social_accounts WHERE sociable_id = 1047;\n\nselect * from activity_searches where id = 10932;\nselect * from activity_search_filters where activity_search_id = 10932;\nselect * from automated_reports order by id desc;\nselect * from automated_report_results order by id desc;\nselect * from automated_reports where id IN (55);\nselect * from automated_report_results where id IN (81);\nselect * from users where id IN (10633, 13987, 11985);\nselect * from users where group_id IN (3710);\n\nSELECT * FROM automated_reports WHERE uuid_to_bin('18a06a75-afd2-476f-aadc-14d4057bdda2') = uuid;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('582d4b50-8cd3-42a9-9819-d676ff8f3b43') = uuid;\n\nselect * from teams;\nselect * from accounts where team_id = 1;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\nSELECT * FROM automated_report_results WHERE uuid_to_bin('82e74956-6144-4cd1-a3d3-af985c3070a4') = uuid;\n\nselect * from teams where id = 1029;\nselect * from crm_configurations where provider = 'pipedrive';\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 = 1029 and sa.provider = 'pipedrive';\n\n[\n {\n \"user_id\": \"23460 (owner)\",\n \"email\": \"integration-account@pipedrive.jiminny.com\",\n \"id\": 69,\n \"sociable_id\": 23460,\n \"provider_user_id\": \"19555731\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:rYyABXmXsBhEdYU_dfmDH8GF-vzSseJXE5bds_zAyVdAwlTXOPdTl9i4PS4jVofLvpq7IRgvEt2BzGhR6cWiQXHHD0AtayQOkZm262ClFCsMYtKGfep0Jq1n0eiRIVqT9gAY7rWvhpEDF8oAlgnRGmqx-euIkpzE79sPXh4OjNx_yUIaanjyplGpBBJ_NiACd1sMlZmseyUyyU_gldqlCBAuK9hhATc9icgg7zuoc7nKBBrlg49tRtzEagDh6xbFBpzfCp7kE_7n4TLWfWHLPMzu-bktjwA969G9sFRmoH1GjPA0a2odDT4dk1_1ouBrB1NcTT2hQUqH-_RzDW2nWmeoVHA\",\n \"provider_refresh_token\": \"5034113:19555731:87c14258f0c813d02767ee975f6044d46b6b2bfc\",\n \"expires\": 1779091997,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"connected\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 08:23:28\",\n \"updated_at\": \"2026-05-18 07:13:18\",\n \"provider_user_token_encrypted\": \"eyJpdiI6Ik9oYzBwcTVteWN4ajBRaDdMb0FjWGc9PSIsInZhbHVlIjoiQUNMbjU5UHR2Q1RnbWRXMEU1TUx6UVpRU3gzdVc5WktmTE4rVlhXa3lRaGhyUUlZMVZRWEJuR0JaWWhZZXNPRlBuanhuYU5MVHZ5TG9NTVVjNjJSUUpZZ2VhbGYxbHg0UzJEdTVmQjNFZnJRZkMwYjd0N2RMZ05GRS9IR3c2K0NoVjBjYTA5UG12SkxHeDlDMGVNN3ptUWUzblFiTngyYzR1eUpHSEYrdEwvZm0yZklGYjBSNEtTR2ZGazhLM1hqT3lVbjFobDNPZ0d3anFlcjhKcXpERlZGOVN1YmFyNDIvM1BFRDFMYnp4WEI4TGVLM2xYcy9CL0RDOWlQNHI3N0NwWnJPMWRtZllmM2ZKeE9TV2NBeDZxL2M1YnlSVzd3ZW96T3F1QmtBYXBHYkUraGcvdCtRajlYZXBjVVBSdFlMUjVPVDVJbDdyenVoWjMrbVJvU3ZZR1dQZ3pqQ3F3aDF2U2xPZWZIN3BCWVFLNXpxQUtDb2pIK0xHc1E3SklSM3Q0VkNSbm9oK2pFK3hLaW54T1dWbEVneUp0RGhhdVBuOFI4MXROc3dZWnFnTUpiaDVMMnZ4QmlRM3k4QWFlMVFWUFYvdGhJQzZBYnhBQmhWa2ZKN1ZhSnhpaExxbmlTemgzUWw3aXJtWjlSMlhmd0lWMDNDN1N3My9Ua0hCL2xqY3RkVFhMSjFJMDRjOE5DWlgrZ3FMVXN6RWlwUE5GWERZdG1xVjVxOFlLRGs2VVJKS3FLeWRxQjYxdDh4Z2JJNXhlWEZ3dkQ4SGtybDNUcndzblFHeVJNRkYraFh2UDFIUTdMQ1BZa3dEU1dBbzk5K0dyT2RNVFBZZUJpRytSck5pYlI1YUZyMmhUNEZCdWxHYmJLREtzbUpjVkhvV0RoejJpbm1SWHlNaXE5M0RhcS94UW9EdFoweWF3bVFVY0dTZWFPSXBmOCtDYndia215cmtyZU1oT0Exam1CV2tPblNhYjY4clVEeUs3anVHUmNHeS9YLzRha1VhbGl3N3lwaDlzZnRhQUZta2s4eFllNHgzRklSRmNyazJ4dlBDMnByNCtBRjNaVjJCTT0iLCJtYWMiOiJkYTQxZDY1OTY2ZTljMTgyZWRhNGEzMGZjZDc2MjBjN2NlNzU2YTViNGQxNWE1NTI2ZmI1MWQyYjQ2ODYxZmEwIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6Imt2bGxlSmxUK05GMjF0dEtPaTMrUlE9PSIsInZhbHVlIjoiUXZHTElZRXkreHFxUU02SnZ4eVBacG9WWTRlVkd0USszV3JyVFlpU2ZaY25GSWo2WFcrRzNlbFRlUXRQczNwSXRCcEdvZEpveG9jMzBDSTgwdnZLQnc9PSIsIm1hYyI6ImQxYWI0NzU5Nzg5MDI4YWVhZmQ4Mjg1YzhkZDQzMjRkYWYwYTdhZTY5MDMxMjc0OWNiYjY0Nzc3NDQ0MTEyY2EiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300786192D9D96DD60D3D1EBC9DFAEE5F0C45EE80165CF3F3D2B3B627026AA7CFC7CA0128DD463535D32EE491ADBADF8B07596B0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040C7FB1319048ECB2EA3F23B995020110802B52D22F5EAD341AB238FBBCB6093156E443876A664BA5555D722565C2B2D04422C868CD7350555E3CC74221\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n },\n {\n \"user_id\": \"23463\",\n \"email\": \"jiminny_web_sa@pipedrive.jiminny.com\",\n \"id\": 72,\n \"sociable_id\": 23463,\n \"provider_user_id\": \"23270841\",\n \"provider_user_token\": \"v1u:AQIBAHj-LzTNK2yuuuaLqifzhWb9crUNKTpk4FlQ9rjnXqp_6AEQhDhDQVa1nvWCHEvnpvSEAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMnG8KNcZLIjEnlRPxAgEQgDsGPIcKjsMU7Qel36BtM5FCQa56mYUy24_AAoqd12yjVFkq6egLqS0inp-5G4JE7frJURMV8VTw_fY14g:txqCuWLeVhgwiaFqXIvQWWrtrnFIy_4lT3VCr-sRB4g6_2lK8KcQ_6ka_qFmZhr-IeIAKmAImx6H1iIKx4Ab7XZ5MnKIh03GKbHjI0n0rGT9UYkeH21jKOxJvKaSX_TyLbxFPR6irPQyvqcpBClXI52gVJH01KzZy_dMTHFXhhDLOIhEpSrQXHG7Qo8q7OuBeSPZrU1ALi9kmAm4GTpzGTbzfl-hUt9IAfPunJOCyv3mf2Tl-MT8EyQgOFPrsP3yz9UlSyVhb40zO_bCnUrqNxjwgm_E6vgpVrwULTQbHe-43Dq-TRetjceUzT88GBgVJ0UdxXP5BRBVXcL5ir8-9ZTMaNU\",\n \"provider_refresh_token\": \"5034113:23270841:34790b44838f5fd422c2d2c82e00f1ecf2178ad1\",\n \"expires\": 1753837219,\n \"refresh_token_expires\": null,\n \"provider\": \"pipedrive\",\n \"state\": \"full-refresh\",\n \"auth_scope\": \"base,deals:full,activities:full,contacts:full,search:read\",\n \"retry_after\": null,\n \"created_at\": \"2025-04-16 10:41:12\",\n \"updated_at\": \"2025-07-30 01:00:17\",\n \"provider_user_token_encrypted\": \"eyJpdiI6InVEVEl2SzIxMjd1bkNDWG9lY3YvQ0E9PSIsInZhbHVlIjoiRlJLbDZ3ZHo2dHMxUWQwdGU2YUZjV3lPWHlxQTJ0eWh4S0RTMjlSaThVcktoaWhXcTd2UXl4Mjg4bW5UUnZCZEQ5NXpuQTVKOURiMDNIa3l3K0lSWCt5azRBOEdHbitWQXhxeEpMVUZ1dnF2NVl1TTZLelZOaGNvRlBLeGpIWlpoRGloUEprd2xoNUFPcTlLcUd3WVlUU2svR1NOeXBYQ2NnMWhnK1V2aytOeVVMNzJGdVZXMU1JS3BSaGNCcmxkVjEwQ01mQXNBdWNhS1lMZWZobnZwcHBkN1R4bUVDRUNYdnNtSVJkdG5MdkN3djJBT0hMRDl1MHFGbnl4WU13ejBkUWsrdUljWkZhcTJlN0JDSGdTVzlPY0FGMUJlZi9WRGpkMUk5R20wblYwSk9VR2FuaHpLTzJNeitMbnF1V1NEMUUxRmYzaDRGZDMyaXd3Z0FjQno4SzVoYjUyTmV3UXNpRlF4TGZKNVl3dUFqdGhKVWJjRVlUUXRGalBpaXJvSGJmbS8rd25aQ2Zvc05saHRDRjlHV1VEUFFiRU5xbWRVNkxFSXV0RUZyaUlYNWMwMmhnZ0Y1VUQ4eEFkY2QyWXpnR0NidkVJSWdjVGljUjA3NDdpZW9WUHhtSlpGSGdNU2hRUTA5ZW03RGpiRFdrdytkOHJXSUxlazZNaG9iaUg2NFZYdEc3YklMeFZvblBzWmVRSDcvN2M4WUNtL3h4S2IrUW00cXhialBia3BJcW5XallBNlV5WWdhcE1ZVFBBM3RSSUVBamYvOGZEQWM5a2FJMGwyWkRSU3dlTEtPemZlQ3RXRGNDcEdYRHdMNTlTQVg2SUdUN0hVaXdZT1dUOUlrVzkrZHFBemhwWXg1cm4rSy9UOHUzcnNSM2dISlhBRTEyVUNyTkZYaFJYUlN1a2RKVHhhM2dHckR3a1JGaVZ2Wk9BVnhTclVpSEhwWTVpQTlJbXVkOUxSTGpRbDk0a1VtbE9QMVAvN3VlVEhJUHd2elowd0laNVIzZ3M3N0ZOK0NDakIwQ2FicGxoMDBhTXI0VUppUmFOZHdlWUdGV21NNFQ4RU1nY0dnWT0iLCJtYWMiOiI0ZTU4ZmJkNTdkYmY0NGE4NTJjZjlhNDExNzE2YjhlOWM2NTA5OGY2MDA4OTcyZDVlOTljY2JjZDhmMjBhMDUyIiwidGFnIjoiIn0=\",\n \"provider_refresh_token_encrypted\": \"eyJpdiI6IkJGMkdRVHRKM2VTcitKNGcvQWJtUGc9PSIsInZhbHVlIjoicmFyRkxPZ1Rybm1ORXlEVjJ2TXFGTzJtM3hWaFhnUVVHN2ZlR1lRM0I5d3ozbnZTcU5EdzJqRkI2elhyNWhlenRTUXV3bjk0N1JXeklDMVAyUzBKcHc9PSIsIm1hYyI6ImJhODVjMGQyZDE3Y2ExNjc2OWVjYWJiNmFjYWVkODIyMTMyNWVhYTExMTgwYTEyMTU0MzUzZGE1YjQ5YzQ5ZjEiLCJ0YWciOiIifQ==\",\n \"encryption_key\": \"0x01020300788C37CDF66ABE9301A68D5D4866AC0C197E04EEE4D904F20A59991322EBAE252301BEF4B24FF01359E934E5654617E4EEAC0000006E306C06092A864886F70D010706A05F305D020100305806092A864886F70D010701301E060960864801650304012E3011040CEB00EF45BDEA999A5558889E020110802B925F372F7BEFAF0B45E48686113D1DA430ECFCC07B1F61BA6828CC44235278EDB05C486E8068D0BE737D91\",\n \"sociable_type\": \"user\",\n \"owner_id\": 23460\n }\n]","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7498689834597179426
|
6686367646540542029
|
idle
|
accessibility
|
NULL
|
Project: faVsco.js, menu
master, menu
Start Listen Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
9
1
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Component\Twilio\Conference\ConferenceManager;
use Illuminate\Database\Eloquent;
use Illuminate\Support\Str;
use Jiminny\Component\ElasticSearch\Model\Observer;
use Jiminny\Component\Twilio\Conference\ConferenceManager;
use Jiminny\Component\Twilio\Exception\OutOfBoundsException;
use Jiminny\Component\Twilio\Exception\UnexpectedValueException;
use Jiminny\Component\Twilio\Resolver;
use Jiminny\Component\Twilio\VO;
use Jiminny\Component\UrlGenerator\Webhook;
use Jiminny\Events;
use Jiminny\Exceptions\LogicException;
use Jiminny\Models;
use Jiminny\Models\Participant\Connection;
use Jiminny\Services\ActivityService;
use Jiminny\Services\Activity\CrmOwnerResolver;
use Jiminny\Services\Crm\CachedCrmServiceDecorator;
use Jiminny\Services\Crm\ProviderRegistry;
use Jiminny\Services\Telephony\TwilioClientBuilder;
use Psr\Log\LoggerInterface;
use Twilio\Exceptions\ConfigurationException;
use Twilio\Exceptions\RestException;
use Twilio\Exceptions\TwilioException;
use Twilio\TwiML;
final readonly class SoftPhoneManager implements ConferenceManager
{
public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;
public const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';
public function __construct(
private ProviderRegistry $crmProviderRegistry,
private Webhook $urlGenerator,
private ActivityService $activityService,
private LoggerInterface $logger,
private TwilioClientBuilder $twilioClientBuilder,
) {
}
public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'data' => $data,
'instanceof' => get_class($data),
]);
$activity = Observer::skipEvents(function () use ($data) {
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundCreate) {
$activity = $this->createInboundActivity($data);
} elseif ($data instanceof VO\ConferenceManager\SoftPhoneOutboundCreate) {
$activity = $this->createOutboundActivity($data);
} else {
throw new LogicException(sprintf(
'Unknown softphone implementation: %s',
get_class($data)
));
}
return $activity;
});
$this->logger->debug(__METHOD__ . ': done', [
'instanceof' => get_class($data),
'activity' => $activity->id_string,
]);
return $activity;
}
private function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\Activity
{
$startTime = microtime(true);
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
$now = now();
$user = $data->getUser();
$team = $user->getTeam();
$device = $data->getDevice();
$phoneNumber = $data->getPhoneNumber();
$route = $data->getPhoneRoute();
if (! $this->activityService->teamCanDial($team, $phoneNumber)) {
$region = getRegionByNumber($phoneNumber, $user->getCountryCode());
throw new LogicException(sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? 'this number'
));
}
$lead = null;
$account = null;
$contact = null;
$stage = null;
$opportunity = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $team,
'integrationAdmin' => $user,
'providerSlug' => $team->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
} catch (\Throwable $throwable) {
$this->logger->error('[SoftPhoneManager] Failed to resolve CRM service with fallback', [
'exception' => $throwable,
'user_id' => $user->getId(),
'team_id' => $team->getId(),
]);
$crmService = $this->crmProviderRegistry->get($team->crm->provider);
if (! $user->isCrmRequired()) {
$crmService->setUser($user->team->owner);
} else {
$crmService->setUser($user);
}
}
$prospectId = $data->getProspectId();
try {
if ($prospectId !== null) {
$crmStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM parseRecords', [
'prospect_id' => $prospectId,
'object_type' => $data->getObjectType(),
]);
[$lead, $account, $opportunity, $contact, $stage] = $crmService->parseRecords(
$prospectId,
$data->getObjectType()
);
$this->logger->info('[SoftPhoneManager] CRM parseRecords completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'parse_duration_ms' => round((microtime(true) - $crmStart) * 1000, 2),
'found_lead' => $lead !== null,
'found_account' => $account !== null,
'found_opportunity' => $opportunity !== null,
'found_contact' => $contact !== null,
]);
// Try to attach a contact if we have an opportunity.
if ($opportunity !== null && $contact === null) {
$matchStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting CRM matchByPhone');
[, , , $contact, ] = $crmService->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
$this->logger->info('[SoftPhoneManager] CRM matchByPhone completed', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'match_duration_ms' => round((microtime(true) - $matchStart) * 1000, 2),
'found_contact' => $contact !== null,
]);
}
} else {
$decorator = resolve(CachedCrmServiceDecorator::class);
$decorator->setCrmService($crmService);
[$lead, $account, $opportunity, $contact, $stage] = $decorator->matchByPhone(
$data->getPhoneNumber(),
$data->getRawPhoneNumber(),
$user->getId()
);
}
} catch (\Throwable $throwable) {
$this->logger->error('[' . $crmService->getDisplayName() . '] Error looking up customer', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an outbound call from happening.
}
if ($data->hasProspectStage()) {
/** @var Models\Stage $stage */
$stage = $team->crm->stages()->uuid($data->getProspectStage());
}
$dbStart = microtime(true);
$this->logger->info('[SoftPhoneManager] Starting activity creation in DB');
$activity = $user->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE,
'provider' => Models\Activity::PROVIDER_TWILIO,
'device_id' => $device->id ?? null,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'value' => $opportunity ? $opportunity->value : null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_PENDING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $phoneNumber),
'scheduled_start_time' => $now,
]);
$this->logger->info('[SoftPhoneManager] Activity created in DB', [
'elapsed_ms' => round((microtime(true) - $startTime) * 1000, 2),
'db_duration_ms' => round((microtime(true) - $dbStart) * 1000, 2),
'activity_id' => $activity->id ?? null,
]);
if (! $activity instanceof Models\Activity) {
throw new LogicException('Activity model expected');
}
$regionId = null;
if ($user->hasRegionId()) {
$regionId = $user->getRegionId();
} elseif ($data->hasRegion()) {
$regionId = $data->getRegion()->getId();
}
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $regionId,
'is_muted' => false,
]);
$phoneRouteResolver = new Resolver\PhoneRouteResolver($user, $route);
$phoneNumberOrigin = $phoneRouteResolver->getPhoneNumberOrigin();
$connectionType = $phoneRouteResolver->getConnectionType();
$callerId = $this->determineUserCallerId($user);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'user_id' => $user->id,
'email' => $user->email,
'name' => $user->name,
'phone_number' => $phoneRouteResolver->mustUsePSTN()
? $phoneNumberOrigin
: $callerId,
]);
$caller->connections()->create([
'session_id' => $session->getId(),
'direction' => $phoneRouteResolver->mustUsePSTN() ? 'outbound-api' : 'outbound',
'phone' => $callerId,
'type' => $connectionType,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $phoneNumber,
'name' => $activity->prospect_name,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'phone' => $phoneNumber,
'direction' => 'outbound-api',
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$activity->refresh();
$this->logger->info('[SoftPhoneManager] createOutboundActivity completed', [
'total_duration_ms' => round((microtime(true) - $startTime) * 1000, 2),
'activity_id' => $activity->id_string,
]);
$this->logger->debug(__METHOD__ . ': done', [
'data' => $data,
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
return $activity;
}
private function createInboundActivity(VO\ConferenceManager\SoftPhoneInboundCreate $data): Models\Activity
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$roomOwner = $data->getUser();
$team = $roomOwner->getTeam();
$phoneNumber = $roomOwner->getSoftPhoneInboundDestinationNumber();
$callerId = $data->getCallerId();
$callerCallSid = $data->getCallSid();
$now = now();
if (! $this->activityService->teamCanDial($roomOwner->getTeam(), $roomOwner->softphone_inbound_destination)) {
$region = getRegionByNumber($roomOwner->softphone_inbound_destination, $roomOwner->getCountryCode());
throw new LogicException(
sprintf(
'Sorry, dialing %s is not available with your subscription.'
. ' Please contact your manager to enable additional destinations.',
$region ?? ' this number',
),
);
}
$lead = $account = $opportunity = $contact = $stage = null;
try {
$crmResolver = app(CrmOwnerResolver::class, [
'team' => $roomOwner->getTeam(),
'integrationAdmin' => $roomOwner,
'providerSlug' => $roomOwner->getTeam()->getCrmConfiguration()->getProviderName(),
]);
$crmService = $crmResolver->prepareCrmService();
[$lead, $account, $opportunity, $contact, $stage] = $crmService->matchByPhone(
$callerId,
null,
$roomOwner->getId()
);
} catch (\Throwable $throwable) {
$this->logger->error(__METHOD__ . ': crm exception', [
'exception' => $throwable,
]);
// maybe their crm is disconnected, but this shouldn't prevent an inbound call from happening
}
/** @var Models\Activity $activity */
$activity = $roomOwner->activities()->create([
'type' => Models\Activity::TYPE_SOFTPHONE_INBOUND,
'provider' => Models\Activity::PROVIDER_TWILIO,
'crm_configuration_id' => $team->crm_id,
'lead_id' => $lead->id ?? null,
'account_id' => $account->id ?? null,
'contact_id' => $contact->id ?? null,
'opportunity_id' => $opportunity->id ?? null,
'stage_id' => $stage->id ?? null,
'status' => Models\Activity::STATUS_RINGING,
'recording_state' => Models\Activity::RECORDING_OFF,
'recording_reason_code' => $this->getVoiceRecordingReasonCode($team, $callerId),
'scheduled_start_time' => $now,
]);
/** @var Models\Session $session */
$session = $activity->sessions()->create([
'type' => Models\Session::TYPE_DIALER,
'region_id' => $roomOwner->getRegionId(),
'is_muted' => false,
]);
/** @var Models\Participant $caller */
$caller = $activity->participants()->create([
'lead_id' => $activity->lead_id ?? null,
'contact_id' => $activity->contact_id ?? null,
'phone_number' => $callerId,
'name' => $activity->prospect_name,
'enter_time' => $now,
]);
$caller->connections()->create([
'telephony_provider_id' => $callerCallSid,
'session_id' => $session->getId(),
'phone' => $callerId,
'direction' => 'inbound',
'type' => Connection::TYPE_PSTN,
'opened_at' => $now,
]);
/** @var Models\Participant $callee */
$callee = $activity->participants()->create([
'user_id' => $roomOwner->id,
'email' => $roomOwner->email,
'name' => $roomOwner->name,
'phone_number' => $phoneNumber,
]);
$callee->connections()->create([
'session_id' => $session->getId(),
'direction' => 'outbound-api',
'phone' => $phoneNumber,
'type' => Connection::TYPE_PSTN,
]);
$activity->update([
'from_participant_id' => $caller->id,
'to_participant_id' => $callee->id,
]);
$this->logger->debug(__METHOD__ . ': done', [
'callSid' => $data->getCallSid(),
'activity' => $activity->id_string,
'session' => $session->id_string,
'caller' => $caller->id_string,
'callee' => $callee->id_string,
]);
$activity->refresh();
return $activity;
}
private function getVoiceRecordingReasonCode(Models\Team $team, string $phoneNumber): int
{
$this->logger->debug(__METHOD__, [
'team' => $team->id_string,
'phone' => $phoneNumber,
]);
if (
! $team->hasComplianceModeRecordingPrompt()
&& ! $team->hasComplianceModeRecordingRestrictToOneSide()
&& ! $team->hasComplianceModeRecordingRestrictRecording()
) {
return 0;
}
/** @var Models\VoiceConsentPrefix|null $voiceConsentPolicy */
$voiceConsentPolicy = Models\VoiceConsentPrefix::query()
->whereRaw("? LIKE CONCAT(destination_prefix, '%')", [$phoneNumber])
->where(static function (Eloquent\Builder $builder) use ($team): void {
$builder
->whereNull('team_id')
->orWhere('team_id', $team->getId());
})
->orderByDesc('team_id')
->first();
if (! $voiceConsentPolicy instanceof Models\VoiceConsentPrefix || $voiceConsentPolicy->isAllowed()) {
return 0;
}
if ($team->hasComplianceModeRecordingPrompt()) {
// This number requires consent from the other party before recording the call.
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_PROMPT;
}
if ($team->hasComplianceModeRecordingRestrictToOneSide()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT_ONE_SIDE;
}
if ($team->hasComplianceModeRecordingRestrictRecording()) {
return Models\Activity::FLAG_RECORDING_REASON_COMPLIANCE_RESTRICT;
}
return 0;
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOrganiser(Models\Activity $activity): void
{
$this->logger->debug(__METHOD__, [
'activity' => $activity->id_string,
]);
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$canBeDialed =
$activity->isTypeSoftPhone()
&& ! $activity->hasStarted()
&& $activity->isPending()
&& $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->exists();
if (! $canBeDialed) {
throw new OutOfBoundsException('Cannot make an outbound call to this activity.');
}
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->where('type', '=', Connection::TYPE_PSTN)
->whereNull('opened_at')
->firstOrFail();
/** @var Models\Session $session */
$session = $organiserConnection->getSession();
$twilioConferenceSettings = $this->applyDefaultTwilioParticipantSettings($organiserConnection, [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
]);
// What number will the organizer see as caller id
$callerId = $roomOwner->getSoftPhoneNumber();
if ($callerId === null) {
$callee = $activity->participants()->whereNull('user_id')->first();
// This is a bridge call. We make it look like the callee is calling the organizer
$callerId = $callee->phone_number;
}
// What number will the prospect see as caller id
$calleeId = $organiser->getPhoneNumber();
$this->logger->debug(__METHOD__ . ': twilio call', [
'calleeId' => $calleeId,
'callerId' => $callerId,
]);
$twilioParticipant = $twilio->createParticipantInstance(
$session->id_string,
$callerId,
$calleeId,
$twilioConferenceSettings
);
$organiserConnection
->setTelephonyProviderId($twilioParticipant->callSid)
->save();
$session
->setTelephonyProviderId($twilioParticipant->conferenceSid)
->save();
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'session' => $session->id_string,
]);
}
public function dialCoach(Models\Activity $activity, Models\User $user): void
{
throw new \LogicException('Not implemented yet');
}
/**
* @throws ConfigurationException
* @throws TwilioException
*/
public function terminate(VO\ConferenceManager\ActivityTerminate $data): void
{
if (! $data instanceof VO\ConferenceManager\SoftphoneTerminate) {
throw new UnexpectedValueException(sprintf(
'Expecting an instance of "%s", but "%s" given.',
VO\ConferenceManager\SoftphoneTerminate::class,
\get_class($data)
));
}
$this->logger->debug(__METHOD__, [
'activity' => $data->getActivity()->id_string,
'user' => $data->getUser()->id_string,
]);
$activity = $data->getActivity();
$roomOwner = $activity->getUser();
$isCancelling = ! $activity->isInFiniteState() && ! $activity->isInProgress();
if ($isCancelling) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
}
/** @var Models\Session $session */
$session = $activity->sessions->first();
/** @var Models\Participant $organiser */
$organiser = $activity->organizer;
/** @var Connection $organiserConnection */
$organiserConnection = $organiser->connections()
->whereIn('type', [
Connection::TYPE_WEBRTC,
Connection::TYPE_PSTN,
])
->firstOrFail();
if (! $organiserConnection->hasTelephonyProviderId()) {
throw new LogicException(
'Unable to terminate call as we do not yet know the organiser telephony provider id',
);
}
$twilioClient = $this->twilioClientBuilder->build($activity->getTeam());
$twilioClient->terminateVoiceCall($organiserConnection->getTelephonyProviderId());
$session->hasTelephonyProviderId()
&& $twilioClient->terminateConference($session->getTelephonyProviderId());
$this->logger->debug(__METHOD__ . ': done', [
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'session' => $session->id_string,
]);
}
public function answer(VO\ConferenceManager\ActivityAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'data' => $data,
]);
if ($data instanceof VO\ConferenceManager\SoftPhoneInboundAnswer) {
return $this->answerInboundCall($data);
}
if ($data instanceof VO\ConferenceManager\SoftPhoneOutboundAnswer) {
return $this->answerOutboundCall($data);
}
throw new LogicException('Unable to answer - not supported activity answer instance');
}
private function answerInboundCall(VO\ConferenceManager\SoftPhoneInboundAnswer $data): TwiML\VoiceResponse
{
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
]);
$dateTime = now();
$activity = $this->create(
new VO\ConferenceManager\SoftPhoneInboundCreate(
$data->getCallerId(),
$data->getCallSid(),
$data->getUser()
)
);
/** @var Models\Participant $activityGuest */
$activityGuest = $activity->from;
$activityGuest
->setEnterTime($dateTime)
->save();
/** @var Connection $connection */
$connection = $activityGuest->connections()
->where('type', Connection::TYPE_PSTN)
->firstOrFail();
$connection
->setTelephonyProviderId($data->getCallSid())
->setOpenedAt($dateTime)
->save();
event(new Events\Activities\Connections\Opened($connection));
return $this->joinTwilioConference($connection, [
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]);
}
private function answerOutboundCall(VO\ConferenceManager\SoftPhoneOutboundAnswer $data): TwiML\VoiceResponse
{
$connection = $data->getConnection();
$participant = $connection->getParticipant();
$activity = $data->getActivity();
$organiser = $activity->organizer;
$dateTime = now();
$this->logger->debug(__METHOD__, [
'callSid' => $data->getCallSid(),
'connection' => $connection->id_string,
'participant' => $participant->id_string,
'activity' => $activity->id_string,
]);
if (! $participant->hasEnterTime()) {
$participant->update([
'enter_time' => $dateTime,
]);
}
$connection->update([
'is_muted' => $participant->isCoach(),
'opened_at' => $dateTime,
]);
event(new Events\Activities\Connections\Opened($connection));
if ($participant->isCoach()) {
/** @var Connection $roomOwnerConnection */
$roomOwnerConnection = $organiser->connections()->openCall()->firstOrFail();
return $this->joinTwilioConference(
$connection,
[
'coach' => $roomOwnerConnection->getTelephonyProviderId(),
]
);
}
return $this->joinTwilioConference(
$connection,
[
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
'muted' => false,
]
);
}
private function determineUserCallerId(Models\User $user): string
{
if ($user->hasCallerId()) {
return $user->getCallerId();
}
// TODO: We should require a caller id to be verified before using the dialer
return $user->getSoftPhoneNumber() ?? $user->phone;
}
private function isRestExceptionAboutTwilioConferenceNotFound(string $exceptionMessage): bool
{
$startsWith = '[HTTP 404] Unable to create record: The requested resource';
$endsWith = 'was not found';
return Str::startsWith($exceptionMessage, $startsWith)
&& Str::endsWith($exceptionMessage, $endsWith);
}
/**
* @throws RestException
* @throws ConfigurationException
* @throws TwilioException
*/
public function dialOtherParty(Connection $callerConnection): self
{
$session = $callerConnection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$twilio = $this->twilioClientBuilder->build($activity->getTeam());
$this->logger->debug(__METHOD__, [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
if (! $activity->isTypeSoftPhone() && ! $activity->isTypeSoftphoneInbound()) {
throw new UnexpectedValueException('Unexpected activity type');
}
$callee = $activity->to;
$calleeId = $callee->getPhoneNumber();
/** @var Connection $calleeConnection */
$calleeConnection = $callee->connections()
->whereIn('type', [
Connection::TYPE_PSTN,
Connection::TYPE_WEBRTC,
])
->firstOrFail();
$caller = $activity->from;
// we need to take the number from the connection
// as the one we store on participant level might be the one we call to the rep via PSTN mode
$callerId = $callerConnection->getPhoneNumber();
if (! $caller->is($callerConnection->getParticipant())) {
throw new LogicException(sprintf(
'Unexpected caller participant. Expected: "%s", Actual: "%s"',
$caller->id_string,
$callerConnection->getParticipant()->id_string
));
}
$twilioConferenceSettings = [
'muted' => false,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => true,
];
$hasInboundRecording = $activity->isTypeSoftphoneInbound()
&& $roomOwner->checkSoftphoneInboundRecordPreference();
$hasOutboundRecording = $activity->isTypeSoftPhone()
&& $roomOwner->checkSoftphoneOutboundRecordPreference();
$isRecordingEnabled = $hasInboundRecording || $hasOutboundRecording;
$isRecordingRestricted = $activity->hasRecordingReasonCompliancePrompted()
|| $activity->hasRecordingReasonComplianceRestricted();
if ($isRecordingEnabled && ! $isRecordingRestricted) {
$twilioConferenceSettings = array_merge($twilioConferenceSettings, [
'record' => true,
'recordingChannels' => 'dual',
'recordingStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.recording.event'),
'recordingStatusCallbackMethod' => 'POST',
'recordingStatusCallbackEvent' => 'in-progress completed absent',
]);
if ($activity->hasRecordingReasonComplianceRestrictedToOneSideRecording()) {
$twilioConferenceSettings['recordingTrack'] = $activity->isTypeSoftPhone()
? 'outbound'
: 'inbound';
}
}
try {
if ($activity->hasRecordingReasonCompliancePrompted()) {
$this->logger->info('[Softphone] Request compliance prompt via outbound call', [
'activity_uuid' => $activity->getUuid(),
'session' => $session->id_string,
'conference_sid' => $session->getTelephonyProviderId(),
]);
$callInstance = $twilio->createCall(
$callerId,
$calleeId,
$this->urlGenerator->route('jiminny.webhook.softphone.compliance.prompt', [
'session' => $session->id_string,
'connection' => $calleeConnection->id_string,
]),
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $callInstance->sid,
'parent_connection_id' => $callerConnection->getId(),
]);
} else {
$twilioParticipantConnection = $twilio->createParticipantInstance(
$session->getTelephonyProviderId(),
$callerId,
$calleeId,
$this->applyDefaultTwilioParticipantSettings($calleeConnection, $twilioConferenceSettings)
);
$calleeConnection->update([
'telephony_provider_id' => $twilioParticipantConnection->callSid,
]);
}
} catch (RestException $restException) {
if (! $this->isRestExceptionAboutTwilioConferenceNotFound($restException->getMessage())) {
throw $restException;
}
if (! $activity->isInFiniteState()) {
$activity
->setStatus(Models\Activity::STATUS_CANCELLED)
->save();
$message = __METHOD__ . ': activity.status -> cancelled';
} else {
$message = sprintf(
__METHOD__ . ': not setting to cancelled, activity.status is %s',
$activity->getStatus()
);
}
$this->logger->info($message, [
'activity' => $activity->id_string,
'exception' => $restException,
]);
}
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
'connection' => $callerConnection->id_string,
]);
return $this;
}
private function applyDefaultTwilioParticipantSettings(Connection $connection, array $override = []): array
{
$session = $connection->getSession();
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => true,
'endConferenceOnExit' => false,
'record' => false,
'waitUrl' => '',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]),
'statusCallbackEvent' => [
'initiated',
'ringing',
'answered',
'completed',
],
'statusCallbackMethod' => 'POST',
'conferenceStatusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
]),
'conferenceStatusCallbackMethod' => 'POST',
'conferenceStatusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function applyDefaultTwilioConferenceSettings(Models\Session $session, array $override = []): array
{
$default = [
'beep' => false,
'muted' => true,
'startConferenceOnEnter' => false,
'endConferenceOnExit' => false,
'waitUrl' => '',
'statusCallbackEvent' => implode(' ', [
'start',
'end',
'join',
'leave',
'mute',
'hold',
// 'speaker',
]),
'statusCallbackMethod' => 'POST',
'statusCallback' => $this->urlGenerator->route('jiminny.webhook.softphone.conference.event', [
'session' => $session->getIdString(),
]),
];
if ($session->hasRegion()) {
$default['region'] = $session->getRegion()->getName();
}
return array_merge($default, $override);
}
private function joinTwilioConference(Connection $connection, array $options = []): TwiML\VoiceResponse
{
$session = $connection->getSession();
$activity = $session->getActivity();
$roomOwner = $activity->getUser();
$this->logger->debug(__METHOD__, [
'connection' => $connection->id_string,
'session' => $session->id_string,
'activity' => $activity->id_string,
'user' => $roomOwner->id_string,
]);
$voiceResponse = new TwiML\VoiceResponse();
$voiceResponse->dial()
->setAction($this->urlGenerator->route('jiminny.webhook.softphone.participant.event', [
'connection' => $connection->id_string,
]))
->conference(
$session->getIdString(),
$this->applyDefaultTwilioConferenceSettings($session, $options)
);
$this->logger->debug(__METHOD__ . ': done', [
'session' => $session->id_string,
'result' => $voiceResponse,
]);
return $voiceResponse;
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny_jupiter
Sync Changes
Hide This Notification
Code changed:
Hide
19
19
17
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM teams WHERE id = 1;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 283;
SELECT * FROM crm_fields WHERE id = 2234;
SELECT * FROM crm_field_values WHERE crm_field_id = 2234;
select * from crm_profiles where user_id = 143;
select * from record_types where crm_configuration_id = 39; # 0121K000001MHElQAO,0121K000001MHEqQAO
select * from business_processes where crm_configuration_id = 39;
# 01941000000H669AAC, 01941000000H66JAAS
select * from record_type_field_values
where record_type_id IN (24);
select * from crm_field_values where id IN (2730);
select * from crm_configurations where id = 39;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce'; #1035
select * from users where team_id = 1; # 222 group 3
SELECT * FROM activities WHERE user_id = 222 order by id desc;
select * from sidekick_settings where team_id = 1;
select * from teams where id = 1;
select * from team_features where team_id = 1;
select * from activities where crm_configuration_id = 2
and provider = 'ms-teams' and id = 608765;
SELECT * FROM activities WHERE crm_configuration_id = 2 and crm_provider_id = '59523413338';
select * from sidekick_settings where team_id = 2;
SELECT * FROM activities WHERE id = 608660;
select * from activity_summary_logs where activity_id = 608660;
select * from ai_prompts where transcription_id = 11214;
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('ed78a437-2804-450e-ab2f-56ab1c641346') = uuid;
# id: 608818, crm: 59628809737
SELECT * FROM activities WHERE uuid_to_bin('36b06e55-afdd-4782-8dee-c624cd0af191') = uuid;
# id: 608821, crm: 59632069252
SELECT ce.start_time, ce.end_time, a.id, a.uuid, crm_provider_id, calendar_event_id, title,
playbook_category_id, user_id, lead_id, contact_id, account_id, opportunity_id,
scheduled_start_time, scheduled_end_time, actual_start_time, actual_end_time, a.created_at
FROM activities a
join calendar_events ce on a.calendar_event_id = ce.id
WHERE a.id IN (608818, 608821);
select * from users where team_id = 1;
select * from team_settings where team_id = 1;
select * from crm_profiles where crm_configuration_id = 39 order by user_id;
select * from team_features where team_id = 1;
select * from users where team_id = 2;
SELECT * FROM activities WHERE uuid_to_bin('ec7647e9-5225-458b-b475-f31aa2769204') = uuid; # 612639
# Preslava N. Ivanova, grou id 3
SELECT * FROM opportunities WHERE uuid_to_bin('a2928fe5-aec5-46cb-85d9-7654c89e46a6') = uuid;
select * from activities where opportunity_id = 344 and actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00';
select
a.id,
a.type,
a.scheduled_start_time,
a.actual_start_time,
a.created_at,
a.opportunity_id,
a.status
FROM activities a
WHERE opportunity_id = 344
and status IN ('completed', 'received', 'delivered')
and (
(a.actual_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.created_at between '2024-10-11 00:00:00' and '2024-10-12 00:00:00')
OR (a.scheduled_start_time between '2024-10-11 00:00:00' and '2024-10-12 00:00:00'))
;
SELECT * FROM users WHERE id = 222;
SELECT * FROM crm_profiles WHERE user_id = 222;
select * from crm_layouts where crm_configuration_id = 39;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 281;
select * from group_deal_risk_types;
select * from opportunities where team_id = 1;
SELECT * FROM opportunities WHERE id = 315;
SELECT * FROM crm_field_data WHERE object_id = 315;
select * from crm_field_data where object_id = 260;
select * from generic_ai_prompts where subject_id = 315;
select * from teams; # 36, 21, 121, [EMAIL]
SELECT * FROM social_accounts WHERE sociable_id = 121 and provider = 'bullhorn';
# [PASSWORD_DOTS]
select * from teams where id = 1;
select * from crm_configurations where id = 39;
select * from users where team_id = 1;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 1;
# 1 - 00541000004281rAAA
# 204 - 0052g000003freeAAA
# 429 - 0052g000003qGOiAAM
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
select * from activities where type = 'softphone'
and created_at > '2024-12-11 15:24:36' order by id desc;
select * from activity_providers where team_id = 1;
select * from activity_provider_users where activity_provider_id = 328;
select * from opportunities where crm_configuration_id = 39
AND account_id = 178 AND is_closed = false
order by created_at DESC;
select * from contacts where id = 3952;
select * from accounts where id = 178;
# [PASSWORD_DOTS]
select * from teams where id = 36;
select * from crm_configurations where id = 21;
select * from users where team_id = 36;
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 36;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 36
and sa.provider = 'bullhorn';
select * from social_accounts where id = 348;
UPDATE social_accounts SET
provider_user_token = '21442_6802599_91:41179a58-21e7-4d7c-ad58-56bb666b2f65',
provider_refresh_token = '21442_6802599_91:01c6b335-3f2a-42e4-85ff-8a08fa65fceb',
expires = 1733998131,
state = 'connected'
WHERE id = 348;
# [PASSWORD_DOTS]
select * from teams where id = 31;
select * from crm_configurations where id = 18;
select * from users where team_id = 31; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 31;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 31
and sa.provider = 'close';
select * from contacts where crm_configuration_id = 18;
# [PASSWORD_DOTS] NEPTUNE [PASSWORD_DOTS]
select * from teams;
select * from users where id IN (1030, 1035, 1052);
select * from crm_configurations;
select * from users where team_id = 65; # 257
select * from team_settings where team_id = 65; # 257
select * from invitations where team_id = 65; # 257
select * from users where email = '[EMAIL]'; # 257
select u.email, cp.* from users u
join crm_profiles cp on u.id = cp.user_id
where u.team_id = 65;
select * from crm_configurations where id = 53;
select * from accounts where crm_configuration_id = 53 order by id desc;
select * from leads where crm_configuration_id = 53 order by id desc;
select * from contacts where crm_configuration_id = 53 order by id desc;
select * from opportunities where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 53 order by id desc;
select * from crm_fields where crm_configuration_id = 53 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 53 order by id desc;
select * from stages where crm_configuration_id = 53 order by id desc;
select * from crm_profiles where crm_configuration_id = 13;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
and sa.provider = 'integration-app';
select * from contacts where crm_configuration_id = 13;
select * from social_accounts where sociable_id = 283;
SELECT * FROM opportunities WHERE crm_provider_id = '006O400000E9bzeIAB';
select * from activity_providers where team_id = 65;
SELECT * FROM activities WHERE crm_configuration_id IN (51, 52, 53);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 65
;
# [PASSWORD_DOTS] STAGING [PASSWORD_DOTS]
SELECT * FROM teams;
SELECT * FROM teams WHERE id = 88;
SELECT * FROM teams WHERE id = 89;
select * from team_settings where team_id = 89;
SELECT * FROM users WHERE team_id = 89;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 89;
select * from users;
SELECT * FROM social_accounts WHERE sociable_id = 1761;
SELECT * FROM crm_configurations WHERE id = 70;
select * from accounts where crm_configuration_id = 70 order by id desc;
select * from leads where crm_configuration_id = 70 order by id desc;
select * from contacts where crm_configuration_id = 70 order by id desc;
select * from opportunities where crm_configuration_id = 70 order by id desc;
select * from crm_profiles where crm_configuration_id = 70 order by id desc;
select * from crm_fields where crm_configuration_id = 70 order by id desc;
select * from crm_field_values where crm_field_id = 3536 order by id desc;
select * from crm_layouts where crm_configuration_id = 70 order by id desc;
select * from stages where crm_configuration_id = 70 order by id desc;
select * from business_processes where crm_configuration_id = 70 order by id desc;
select * from business_process_stages where business_process_id = 34;
select * from contacts where id = 10468;
select * from crm_layouts where crm_configuration_id = 70;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 388;
SELECT * FROM crm_fields WHERE id IN (3533,3534,3535);
select * from activities where crm_configuration_id = 70
and (account_id IS NOT NULL or lead_id IS NOT NULL or contact_id IS NOT NULL or opportunity_id IS NOT NULL) order by id desc;
SELECT * FROM activities WHERE uuid_to_bin('2e10b60f-8a61-41c5-a3d4-28835353dc65') = uuid;
SELECT * FROM activities where crm_configuration_id = 69 ;
SELECT * FROM users WHERE email LIKE '%[EMAIL]%';
SELECT * FROM activities WHERE uuid_to_bin('5a150c93-40fc-42ec-b3bd-c1d328e09f6e') = uuid;
SELECT * FROM opportunities WHERE id = 385;
select * from participants p
join activities a on p.activity_id = a.id
where a.crm_configuration_id = 70
and (p.lead_id IS NOT NULL or p.contact_id IS NOT NULL);
SELECT * FROM participants WHERE id = 1013638;
select * from teams where id = 90;
select * from users where team_id = 90;
select * from social_accounts where social_accounts.sociable_id IN (1960,1760);
SELECT * FROM crm_profiles WHERE crm_configuration_id = 71;
select * from invitations where team_id = 90;
select * from crm_configurations where id = 71;
select * from accounts where crm_configuration_id = 71 order by id desc;
select * from leads where crm_configuration_id = 71 order by id desc;
select * from contacts where crm_configuration_id = 71 order by id desc;
select * from opportunities where crm_configuration_id = 71 order by id desc;
select * from crm_profiles where crm_configuration_id = 71 order by id desc;
select * from crm_fields where crm_configuration_id = 71 order by id desc;
select * from crm_field_values where crm_field_id = 3341 order by id desc;
select * from crm_layouts where crm_configuration_id = 71 order by id desc;
select * from stages where crm_configuration_id = 71 order by id desc;
select * from users order by secondary_email desc;
select u.id, u.email, u.status, sa.id, sa.provider_user_id from social_accounts sa
join users u on sa.sociable_id = u.id
where sa.provider = 'google' and u.email LIKE 'aneliya%';
select * from failed_jobs order by id desc;
select * from users where email = '[EMAIL]' or secondary_email = '[EMAIL]';
select * from teams;
SELECT * FROM crm_profiles WHERE crm_configuration_id = 39;
SELECT * FROM crm_fields WHERE crm_configuration_id = 39 and object_type = 'task';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 1
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM activities WHERE uuid_to_bin('c38b3895-fd0f-4b1f-9fb2-c170dba137c6') = uuid;
SELECT * FROM crm_configurations WHERE id = 70;
select * from teams where id = 1;
select * from groups where team_id = 1;
select * from users where team_id = 1;
select o.id, o.name,o.close_date, u.id, u.name, u.group_id, r.id, r.display_name, g.name, g.scope from opportunities o
join users u on o.user_id = u.id
join groups g on u.group_id = g.id
join...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
60870
|
2168
|
24
|
2026-05-20T08:21:29.413693+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-20/1779 /Users/lukas/.screenpipe/data/data/2026-05-20/1779265289413_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpAPPDOCKERO ₴1L SlackFileEditViewGoHistoryWindowHelpAPPDOCKERO ₴1Last login: Wed May 20 09:14:49on ttys007DEV (-zsh)О ₴2Poetry could not find a pyproject.toml file in /Users/lukas/jiminny/app or its parentsPoetry could notfind a pyproject.toml file in /Users/lukas/jiminny/app or its parentslukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20915-add-domain-specific-emaidocker exec -it docker_lamp_1 bash-c "mv /usr/local/etc/php/conf.d/xdebug.ini ~/xdebug.irWhat's next:Try Docker Debug for seamless, persistentdebugging tools in any container or image →Learn moreat https://docs.docker.com/go/debug-cli/dockerexec-it docker_lamp_1supervisorctlrestartalljiminny-worker-processing-delayed: jiminny-worker-processing-delayed_00: stoppedworker-download:worker-download_00:stoppedjiminny-worker-processing-2:jiminny-worker-processing-2_00: stoppedjiminny-worker-processing-3:jiminny-worker-processing-3_00: stoppedjiminny-worker-processing-4:jiminny-worker-processing-4_00: stoppedjiminny-worker-processing-5:jiminny-worker-processing-5_00: stoppedworker-analytics:worker-analytics_00: stoppedworker-crm-update:worker-crm-update_00: stoppedworker-nudges:worker-nudges_00: stoppedworker-audio:worker-audio_00: stoppedjiminny-worker-processing-1:jiminny-worker-processing-1_00: stoppedworker:worker_00: stoppedworker-calendar:worker-calendar_00:stoppedworker-conferences:worker-conferences_00: stoppedworker-crm-sync:worker-crm-sync_00:stoppedworker-emails:worker-emails_00: stoppedworker-es-update:worker-es-update_00: stoppedartisan-schedule:artisan-schedule_00: stoppedartisan-schedule:artisan-schedule_00: startedjiminny-worker-processing-1:jiminny-worker-processing-1_00: startedjiminny-worker-processing-2:jiminny-worker-processing-2_00: startedjiminny-worker-processing-3:jiminny-worker-processing-3_00: startedjiminny-worker-processing-4:jiminny-worker-processing-4_00: startedjiminny-worker-processing-5:jiminny-worker-processing-5_00: startedjiminny-worker-processing-delayed:jiminny-worker-processing-delayed_00: startedworker:worker_00: startedworker-analytics:worker-analytics_00:startedworker-audio:worker-audio_00: startedworker-calendar:worker-calendar_00:startedworker-conferences:worker-conferences_00: startedworker-crm-sync:worker-crm-sync_00: startedworker-crm-update:worker-crm-update_00: startedworker-download:worker-download_00:startedHomeDMsActivityFilesLater..•More+> 0(ahlED→Jiminny ...Ab External connections* Starred8 jiminny-x-integrati...& platform-inner-teamE Channels# ai-chapter# alerts# backend# bugs# confusion-clinic# curiosity_lab# engineering# general# happy_birthday# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of jimi...• Direct messages8. Aneliya Angelovav Unread mentionsLunch - in 39 m100% <8• Wed 20 May 11:21:29Describe what you are looking forAneliya Angelova6 0• Messagesresponse:Add canvas@ Files+Monday, May 18th ~i nqmam ерpop-ии матчинга след warninga продължиhttps://us-east-2.console.aws.amazon.com/cloudwatch/home?region=us-east-2#logsV2:logs-insights$3FqueryDetail$|.IntlDs~(~'All)~ queryBy~'allLogGroups)Lukas Kovalik 5:10 PMсуперутре ще го деплойна тогаваd 1Today~NewAneliya Angelova 11:11 AMЗдрасти Лукашhttps://app.circleci.com/pipelines/github/jiminny/app/58598/workflows/27f2b2f4-2847-47f0-a79d-9e313cbe278e/jobs/890111фейлва някакьв тестJY-20613-allow-owner-role-on-team-setupLukas Kovalik 11:20 AMздрасти, уж е минал, севга щевид дали нещотрябва да се правиMessage Aneliya Angelova+..•...
|
NULL
|
-3860224011370762838
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpAPPDOCKERO ₴1L SlackFileEditViewGoHistoryWindowHelpAPPDOCKERO ₴1Last login: Wed May 20 09:14:49on ttys007DEV (-zsh)О ₴2Poetry could not find a pyproject.toml file in /Users/lukas/jiminny/app or its parentsPoetry could notfind a pyproject.toml file in /Users/lukas/jiminny/app or its parentslukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20915-add-domain-specific-emaidocker exec -it docker_lamp_1 bash-c "mv /usr/local/etc/php/conf.d/xdebug.ini ~/xdebug.irWhat's next:Try Docker Debug for seamless, persistentdebugging tools in any container or image →Learn moreat https://docs.docker.com/go/debug-cli/dockerexec-it docker_lamp_1supervisorctlrestartalljiminny-worker-processing-delayed: jiminny-worker-processing-delayed_00: stoppedworker-download:worker-download_00:stoppedjiminny-worker-processing-2:jiminny-worker-processing-2_00: stoppedjiminny-worker-processing-3:jiminny-worker-processing-3_00: stoppedjiminny-worker-processing-4:jiminny-worker-processing-4_00: stoppedjiminny-worker-processing-5:jiminny-worker-processing-5_00: stoppedworker-analytics:worker-analytics_00: stoppedworker-crm-update:worker-crm-update_00: stoppedworker-nudges:worker-nudges_00: stoppedworker-audio:worker-audio_00: stoppedjiminny-worker-processing-1:jiminny-worker-processing-1_00: stoppedworker:worker_00: stoppedworker-calendar:worker-calendar_00:stoppedworker-conferences:worker-conferences_00: stoppedworker-crm-sync:worker-crm-sync_00:stoppedworker-emails:worker-emails_00: stoppedworker-es-update:worker-es-update_00: stoppedartisan-schedule:artisan-schedule_00: stoppedartisan-schedule:artisan-schedule_00: startedjiminny-worker-processing-1:jiminny-worker-processing-1_00: startedjiminny-worker-processing-2:jiminny-worker-processing-2_00: startedjiminny-worker-processing-3:jiminny-worker-processing-3_00: startedjiminny-worker-processing-4:jiminny-worker-processing-4_00: startedjiminny-worker-processing-5:jiminny-worker-processing-5_00: startedjiminny-worker-processing-delayed:jiminny-worker-processing-delayed_00: startedworker:worker_00: startedworker-analytics:worker-analytics_00:startedworker-audio:worker-audio_00: startedworker-calendar:worker-calendar_00:startedworker-conferences:worker-conferences_00: startedworker-crm-sync:worker-crm-sync_00: startedworker-crm-update:worker-crm-update_00: startedworker-download:worker-download_00:startedHomeDMsActivityFilesLater..•More+> 0(ahlED→Jiminny ...Ab External connections* Starred8 jiminny-x-integrati...& platform-inner-teamE Channels# ai-chapter# alerts# backend# bugs# confusion-clinic# curiosity_lab# engineering# general# happy_birthday# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of jimi...• Direct messages8. Aneliya Angelovav Unread mentionsLunch - in 39 m100% <8• Wed 20 May 11:21:29Describe what you are looking forAneliya Angelova6 0• Messagesresponse:Add canvas@ Files+Monday, May 18th ~i nqmam ерpop-ии матчинга след warninga продължиhttps://us-east-2.console.aws.amazon.com/cloudwatch/home?region=us-east-2#logsV2:logs-insights$3FqueryDetail$|.IntlDs~(~'All)~ queryBy~'allLogGroups)Lukas Kovalik 5:10 PMсуперутре ще го деплойна тогаваd 1Today~NewAneliya Angelova 11:11 AMЗдрасти Лукашhttps://app.circleci.com/pipelines/github/jiminny/app/58598/workflows/27f2b2f4-2847-47f0-a79d-9e313cbe278e/jobs/890111фейлва някакьв тестJY-20613-allow-owner-role-on-team-setupLukas Kovalik 11:20 AMздрасти, уж е минал, севга щевид дали нещотрябва да се правиMessage Aneliya Angelova+..•...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
60871
|
2169
|
45
|
2026-05-20T08:21:29.536700+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-20/1779 /Users/lukas/.screenpipe/data/data/2026-05-20/1779265289536_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhostormVIewINavicarecodeLaravelKeractorWindowmelp PhostormVIewINavicarecodeLaravelKeractorWindowmelpFV faVsco.js v#12092 on Jy-20613-allow-owner-role-on-team-setup kroledey> Dapp ->1h External Libraries• E° Scratches and Consoles© Client.phpUserInvitationDTOTest.php© ClientTest.php© EditTeamRequest.php xsexistinaFeatures = imolode('.'. FeatureEnum::namesoD:$rules = ['name' => "required', "string', "max:150']"owner_id' = I'required_without:owner_email','uuid:users', resolve(TransferUserAdminRule::' owner_email' => ['required_without:owner_id','email'],'owner_role' →> ['prohibited'],'calendar' => ['required_without:owner_id', 'string' , 'max:150'],'crm' => ['required_without:owner_id','string' , 'max:150'],'features' => ['array'],'features.*' => ['in:' . $existingFeatures],'tier_id' => ['required', 'uvid:tiers'],'partner_id' => ['sometimes','nullable', 'uvid:partners'],$features = $this->input('features');if (in_array(FeatureEnum: :DIALER->name, $features)) {// Add Billing address rulesSide-by-side viewer ~Do not ignoreX 18 B ?n502dd3e2'Level' → env('LOG_LEVEL', 'info'),nath' => storade nath'loas/laravel.100')E custom.logtii jiminny.users [PROD]• |aravel.10g4 SF [jiminny@localhost]© Kernel.phpA console [EU]•Jiminny.users EUl• crm_configurations (EU]A console [STAGING]© SoftPhoneManager.php xHS_Jocal (jiminny@localhost]Textwessagingservice.onp& console [Pkol)public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;public const string COMPLIANCE PROMPTACCEPT DIGTT ='1'public functionconstructprivate ProviderRegistry $crmProviderRegistry,private Webhook SurlGeneratorprivate ActivityService $activityService,private LoggerInterface $logger.private TwilioClientBuilder $twilioClientBuilder,) 4..3public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity{...}private function create0utboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\ActivitLunch • In 33m100% 28• Wed 20 May 11:21:29U UserinvitationDTOTestCascadeFixing TextRelayServic+0 ..The Mockery alias approach is still causing redeclaration issues. Let me try a different approach - use Laravel's DB facadeto mock the database queries instead of mocking the model itself.• TextRelayServiceTest.phpThoughtsLet me use the soy pattern with Mockery instead of alias to avoid redeclaration issues.TextRelavServicelest.ono+12 -11Thouaht for 2slThe soy pattern won't work for static calls. Let me iry usina named mocks with uniaue names to avoid redeclaration.• TextRelavServiceTest.php+12 -12Named mocks won't work for static calls. Let me use Laravel's built-in model mocking with Model::shouldReceive() which Ucaeconnereloallenrmletetec< Code SWF.1.6Local ChangesSheltConsoleChanges 3 filesE.env.local app© JiminnyDebugCommand.php app/Console/Commandspnp logging.onpUnversioned Files 9 files=.env.nikilocal apr= .env.other app© CanAccessAiReportsTest.php tests/Unit/Policies© CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ra tavicon.ico publicEids.txt appTeraw so querv sal aoo© SimulateWebhooksCommand.php app/Console/Commands/Crm/HubspotM+ WEBHOOK FILTERING IMPLEMENTATION.md aodhlde tocurrent version'driver' => 'errorlog'.'Level' →> env('LOG_LEVEL', 'info'),'path" => storage_path('logs/Laravel.Log').'driver' ='single','path' => storage_path('logs/custom.log'),"levelt =s envriind levElt Tinfar)iilChecked out JY-20613-allow-owner-role-on-team-setunlide the active tool windovWorkspace associated with branchJy-20013-allow-owner-role-on-ream-seruo hasbeen restoredRollbackConfiaureWN Windsurf Teamo75:5 UTF-8# 4 spaces...
|
NULL
|
-6276188463500327322
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhostormVIewINavicarecodeLaravelKeractorWindowmelp PhostormVIewINavicarecodeLaravelKeractorWindowmelpFV faVsco.js v#12092 on Jy-20613-allow-owner-role-on-team-setup kroledey> Dapp ->1h External Libraries• E° Scratches and Consoles© Client.phpUserInvitationDTOTest.php© ClientTest.php© EditTeamRequest.php xsexistinaFeatures = imolode('.'. FeatureEnum::namesoD:$rules = ['name' => "required', "string', "max:150']"owner_id' = I'required_without:owner_email','uuid:users', resolve(TransferUserAdminRule::' owner_email' => ['required_without:owner_id','email'],'owner_role' →> ['prohibited'],'calendar' => ['required_without:owner_id', 'string' , 'max:150'],'crm' => ['required_without:owner_id','string' , 'max:150'],'features' => ['array'],'features.*' => ['in:' . $existingFeatures],'tier_id' => ['required', 'uvid:tiers'],'partner_id' => ['sometimes','nullable', 'uvid:partners'],$features = $this->input('features');if (in_array(FeatureEnum: :DIALER->name, $features)) {// Add Billing address rulesSide-by-side viewer ~Do not ignoreX 18 B ?n502dd3e2'Level' → env('LOG_LEVEL', 'info'),nath' => storade nath'loas/laravel.100')E custom.logtii jiminny.users [PROD]• |aravel.10g4 SF [jiminny@localhost]© Kernel.phpA console [EU]•Jiminny.users EUl• crm_configurations (EU]A console [STAGING]© SoftPhoneManager.php xHS_Jocal (jiminny@localhost]Textwessagingservice.onp& console [Pkol)public const int COMPLIANCE_PROMPT_TIMEOUT_SECONDS = 20;public const string COMPLIANCE PROMPTACCEPT DIGTT ='1'public functionconstructprivate ProviderRegistry $crmProviderRegistry,private Webhook SurlGeneratorprivate ActivityService $activityService,private LoggerInterface $logger.private TwilioClientBuilder $twilioClientBuilder,) 4..3public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activity{...}private function create0utboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\ActivitLunch • In 33m100% 28• Wed 20 May 11:21:29U UserinvitationDTOTestCascadeFixing TextRelayServic+0 ..The Mockery alias approach is still causing redeclaration issues. Let me try a different approach - use Laravel's DB facadeto mock the database queries instead of mocking the model itself.• TextRelayServiceTest.phpThoughtsLet me use the soy pattern with Mockery instead of alias to avoid redeclaration issues.TextRelavServicelest.ono+12 -11Thouaht for 2slThe soy pattern won't work for static calls. Let me iry usina named mocks with uniaue names to avoid redeclaration.• TextRelavServiceTest.php+12 -12Named mocks won't work for static calls. Let me use Laravel's built-in model mocking with Model::shouldReceive() which Ucaeconnereloallenrmletetec< Code SWF.1.6Local ChangesSheltConsoleChanges 3 filesE.env.local app© JiminnyDebugCommand.php app/Console/Commandspnp logging.onpUnversioned Files 9 files=.env.nikilocal apr= .env.other app© CanAccessAiReportsTest.php tests/Unit/Policies© CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Ra tavicon.ico publicEids.txt appTeraw so querv sal aoo© SimulateWebhooksCommand.php app/Console/Commands/Crm/HubspotM+ WEBHOOK FILTERING IMPLEMENTATION.md aodhlde tocurrent version'driver' => 'errorlog'.'Level' →> env('LOG_LEVEL', 'info'),'path" => storage_path('logs/Laravel.Log').'driver' ='single','path' => storage_path('logs/custom.log'),"levelt =s envriind levElt Tinfar)iilChecked out JY-20613-allow-owner-role-on-team-setunlide the active tool windovWorkspace associated with branchJy-20013-allow-owner-role-on-ream-seruo hasbeen restoredRollbackConfiaureWN Windsurf Teamo75:5 UTF-8# 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
62323
|
2211
|
14
|
2026-05-20T11:31:27.843148+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-20/1779 /Users/lukas/.screenpipe/data/data/2026-05-20/1779276687843_m2.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormVIewINavigarecodeLaravelKeractorTOOISWindo PhpStormVIewINavigarecodeLaravelKeractorTOOISWindowmelpFV faVsco.js~#12092 on Jy-20613-allow-owner-role-on-team-setup~Projecty> Dapp ~>1h External Libraries> E° Scratches and Consoles© CreateTeamRequest.php © User.php UserInvitationDTOTest.php ©[EMAIL]© ClientTest.php© EditTeamRequest.phpuse Jininny models leamuse Jininny Models user.use lests lesclase.tinal class UserinvitationbTulest extends Testcase"suppont Dally • In 25 m100% L28• Wed 20 May 14:31:27U SmsReceivedTestv+0 ..oublic function testcreate-rominvitat1ono vo1d** @var Invitation Sinvitation *^Sinvitation = Invitation::factory()->createCl'email' =>[EMAIL]','group_id' => 1,'team_id' => 1'role_id' = null,TJP + → Side-by-side viewer -Do not ignorenb8c8eb56 confia/loaaina.oho'Level' → env('LOG_LEVEL', 'info'),nath' => storade nath'loas/laravel.100')Highlight words x 15 B ?• custom.log • laravel.log • SF (jiminny@localhost] • console [STAGING] • HS_local ([iminny@localhost] • console [PROD]jiminny.users (PROD] • Kernel.php • console (EU]• SoftPhoneManager.php• TextMessagingService.php •jiminny.users (EU]crm_conrigurations Eufinal readonly class SoftPhoneManager implements ConferenceManagerpublic const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';CascadeTesting SmsReceivedFix Userinvitationdte44 @ >public function __constructCprivate ProviderRegistry $crmProviderRegistry,private Webhook $urlGenerator,private ActivityService $activityService,private LoggerInterface $logger,private TwilioClientBuilder $twilioClientByftder,public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activityf.;C Fix UserinvitationDTotest© Text Relay Email Alias Setup and Filteringprivate function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\ActivitAsk anything &+L< Code SWF.1.6SstantTime = microtime(as float: true);Open editors and positionscurrent versioncascade code X+ .Kick off a new project. Make changesacross vour entire codebaseLocal ChangesSheltConsoleChanges 3 filesE.env.local app© JiminnyDebugCommand.php app/Console/Commandspnp logging.onp contieUnversioned Files 9 files= .env.nikllocal aoeE.env.other apd© CanAccessAiReportsTest.php tests/Unit/Policies© CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Reporfavicon.ico publicE ids.txt appT raw sal querv sal apr.© SimulateWebhooksCommand.php app/Console/Commands/Crm/HubspotM. WEBHOOK FILTERING IMPLEMENTATION.md aoo1 differenceCancel'Level' →> env('LOG_LEVEL', 'info'),'path" => storage_path('Logs/Laravel.Log').'driver' ='single','path' => storage_path('logs/custom.log'),"leveli =s envriind lEVElt Iinfar)Checked out JY-20613-allow-owner-role-on-team-setunW Windsurf Toamo58.6 /171 charc 7 line hreakcl UTF.8f?4 spaces...
|
NULL
|
7414690434325881308
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormVIewINavigarecodeLaravelKeractorTOOISWindo PhpStormVIewINavigarecodeLaravelKeractorTOOISWindowmelpFV faVsco.js~#12092 on Jy-20613-allow-owner-role-on-team-setup~Projecty> Dapp ~>1h External Libraries> E° Scratches and Consoles© CreateTeamRequest.php © User.php UserInvitationDTOTest.php ©[EMAIL]© ClientTest.php© EditTeamRequest.phpuse Jininny models leamuse Jininny Models user.use lests lesclase.tinal class UserinvitationbTulest extends Testcase"suppont Dally • In 25 m100% L28• Wed 20 May 14:31:27U SmsReceivedTestv+0 ..oublic function testcreate-rominvitat1ono vo1d** @var Invitation Sinvitation *^Sinvitation = Invitation::factory()->createCl'email' =>[EMAIL]','group_id' => 1,'team_id' => 1'role_id' = null,TJP + → Side-by-side viewer -Do not ignorenb8c8eb56 confia/loaaina.oho'Level' → env('LOG_LEVEL', 'info'),nath' => storade nath'loas/laravel.100')Highlight words x 15 B ?• custom.log • laravel.log • SF (jiminny@localhost] • console [STAGING] • HS_local ([iminny@localhost] • console [PROD]jiminny.users (PROD] • Kernel.php • console (EU]• SoftPhoneManager.php• TextMessagingService.php •jiminny.users (EU]crm_conrigurations Eufinal readonly class SoftPhoneManager implements ConferenceManagerpublic const string COMPLIANCE_PROMPT_ACCEPT_DIGIT = '1';CascadeTesting SmsReceivedFix Userinvitationdte44 @ >public function __constructCprivate ProviderRegistry $crmProviderRegistry,private Webhook $urlGenerator,private ActivityService $activityService,private LoggerInterface $logger,private TwilioClientBuilder $twilioClientByftder,public function create(VO\ConferenceManager\ActivityCreate $data): Models\Activityf.;C Fix UserinvitationDTotest© Text Relay Email Alias Setup and Filteringprivate function createOutboundActivity(VO\ConferenceManager\SoftPhoneOutboundCreate $data): Models\ActivitAsk anything &+L< Code SWF.1.6SstantTime = microtime(as float: true);Open editors and positionscurrent versioncascade code X+ .Kick off a new project. Make changesacross vour entire codebaseLocal ChangesSheltConsoleChanges 3 filesE.env.local app© JiminnyDebugCommand.php app/Console/Commandspnp logging.onp contieUnversioned Files 9 files= .env.nikllocal aoeE.env.other apd© CanAccessAiReportsTest.php tests/Unit/Policies© CreateMockAskJiminnyReportResultCommand.php app/Console/Commands/Reporfavicon.ico publicE ids.txt appT raw sal querv sal apr.© SimulateWebhooksCommand.php app/Console/Commands/Crm/HubspotM. WEBHOOK FILTERING IMPLEMENTATION.md aoo1 differenceCancel'Level' →> env('LOG_LEVEL', 'info'),'path" => storage_path('Logs/Laravel.Log').'driver' ='single','path' => storage_path('logs/custom.log'),"leveli =s envriind lEVElt Iinfar)Checked out JY-20613-allow-owner-role-on-team-setunW Windsurf Toamo58.6 /171 charc 7 line hreakcl UTF.8f?4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
62324
|
2210
|
10
|
2026-05-20T11:31:29.455732+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-20/1779 /Users/lukas/.screenpipe/data/data/2026-05-20/1779276689455_m1.jpg...
|
PhpStorm
|
faVsco.js – SoftPhoneManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpAPPDOCKER• 81D SlackFileEditViewGoHistoryWindowHelpAPPDOCKER• 81DEV (-zsh)₴82To github.com:jiminny/app.gitc4e163f3e7..f885e531abJY-20613-allow-owner-role-on-team-setup -> JY-20613-allow-owneilukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20613-allow-owner-role-on-team-On branch JY-20915-add-domain-specific-email-text-relayYour branch is up to date with 'origin/JY-20915-add-domain-specific-email-text-relay'.Changes to becommitted:(use "git restore --staged ‹file>..." to unstage)new file:tests/Unit/Notifications/Activities/SmsReceivedTest.phpChanges not staged for commit:Cuse"gitadd‹file›...to updatewhat willbecommitted)Cuse"git restore ‹file›...to discard changesin working directory)modified:.env.localmodified:app/Console/Commands/JiminnyDebugCommand.phpmodified:config/logging.phpUntracked files:Cuse "git add<file>..."to include in what will be committed)env.nikilocalenv.otherWEBHOOK_FILTERING_IMPLEMENTATION.mdapp/Console/Commands/Crm/Hubspot/SimulateWebhooksCommand.phpapp/Console/Commands/Reports/CreateMockAskJiminnyReportResultCommand.phpids.txtpublic/favicon.icoraw_sql_query.sqltests/Unit/Policies/CanAccessAiReportsTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20915-add-domain-specific-emaidocker exec -it docker_lamp_1 ./vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.plPHP CS Fixer 3.87.1 Alexander by Fabien Potencier, Dariusz Ruminskiandcontributors.PHPruntime: 8.3.30Running analysis on 7 cores with 10 files per process.Parallel runner is an experimental feature and may be unstable, use it at your own risk.Loadedconfig default from".php-cs-fixer.dist.php".5690/5690 [100%Fixed 0 of 5690 files in 76.177 seconds, 60.00 MB memory usedWhat's next:Try Docker Debug for seamless, persistent debugging tools in any containeror image »Learn more at https://docs.docker.com/go/debug-cli/lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20915-add-domain-specific-emaiHomeDMsActivityFilesLater...More+(aholSupport Daily • in 29 m100% <78• Wed 20 May 14:31:29→Describe what you are looking forJiminny ...# engineering# general# happy_birthday# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...° Direct messagesP. Nikolay YankovP. Aneliya Angelova. Stoyan Tanevdo James Graham&. Stefka Stoyanova% Galya DimitrovaVasil Vasilev. Stoyan Tomov&: Todor Stamatov. Mario GeorgievLukas Kovalik y...##: AppsToastJira Cloud# ai-chapter8 176 0Messagest Add canvas@ Files+anWednesday, April 22nd~Vasil Vasilev 5:52 PMBinary01full-es-dataset.txtBinaryThis is a single recordVes 6:20 PMjoined #ai-chapter.Nikolay Yankov 7:01 PMhttps://app.jiminny.com/playback/acbbf9e0-6dea-4887-863b-86f7015a687cToday ~NewSteliyan Georgiev 1:59 PMThe Al work we do at Jiminny is mostly in the textmodality, while the voice-to-text transition ishandled by external services.Let's talk about the voice modality during tonight'sAl Chapter call - what it is, how we can utilize it atJiminny, current limitations, etc.To be honest, I'm also fairly new to this, so I'll spendsome time this afternoon preparing myself.d 1Message #ai-chapter+...
|
NULL
|
-8724256430390248965
|
NULL
|
click
|
ocr
|
NULL
|
SlackFileEditViewGoHistoryWindowHelpAPPDOCKER• 81D SlackFileEditViewGoHistoryWindowHelpAPPDOCKER• 81DEV (-zsh)₴82To github.com:jiminny/app.gitc4e163f3e7..f885e531abJY-20613-allow-owner-role-on-team-setup -> JY-20613-allow-owneilukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20613-allow-owner-role-on-team-On branch JY-20915-add-domain-specific-email-text-relayYour branch is up to date with 'origin/JY-20915-add-domain-specific-email-text-relay'.Changes to becommitted:(use "git restore --staged ‹file>..." to unstage)new file:tests/Unit/Notifications/Activities/SmsReceivedTest.phpChanges not staged for commit:Cuse"gitadd‹file›...to updatewhat willbecommitted)Cuse"git restore ‹file›...to discard changesin working directory)modified:.env.localmodified:app/Console/Commands/JiminnyDebugCommand.phpmodified:config/logging.phpUntracked files:Cuse "git add<file>..."to include in what will be committed)env.nikilocalenv.otherWEBHOOK_FILTERING_IMPLEMENTATION.mdapp/Console/Commands/Crm/Hubspot/SimulateWebhooksCommand.phpapp/Console/Commands/Reports/CreateMockAskJiminnyReportResultCommand.phpids.txtpublic/favicon.icoraw_sql_query.sqltests/Unit/Policies/CanAccessAiReportsTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20915-add-domain-specific-emaidocker exec -it docker_lamp_1 ./vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.plPHP CS Fixer 3.87.1 Alexander by Fabien Potencier, Dariusz Ruminskiandcontributors.PHPruntime: 8.3.30Running analysis on 7 cores with 10 files per process.Parallel runner is an experimental feature and may be unstable, use it at your own risk.Loadedconfig default from".php-cs-fixer.dist.php".5690/5690 [100%Fixed 0 of 5690 files in 76.177 seconds, 60.00 MB memory usedWhat's next:Try Docker Debug for seamless, persistent debugging tools in any containeror image »Learn more at https://docs.docker.com/go/debug-cli/lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20915-add-domain-specific-emaiHomeDMsActivityFilesLater...More+(aholSupport Daily • in 29 m100% <78• Wed 20 May 14:31:29→Describe what you are looking forJiminny ...# engineering# general# happy_birthday# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the_people_of_jimi...° Direct messagesP. Nikolay YankovP. Aneliya Angelova. Stoyan Tanevdo James Graham&. Stefka Stoyanova% Galya DimitrovaVasil Vasilev. Stoyan Tomov&: Todor Stamatov. Mario GeorgievLukas Kovalik y...##: AppsToastJira Cloud# ai-chapter8 176 0Messagest Add canvas@ Files+anWednesday, April 22nd~Vasil Vasilev 5:52 PMBinary01full-es-dataset.txtBinaryThis is a single recordVes 6:20 PMjoined #ai-chapter.Nikolay Yankov 7:01 PMhttps://app.jiminny.com/playback/acbbf9e0-6dea-4887-863b-86f7015a687cToday ~NewSteliyan Georgiev 1:59 PMThe Al work we do at Jiminny is mostly in the textmodality, while the voice-to-text transition ishandled by external services.Let's talk about the voice modality during tonight'sAl Chapter call - what it is, how we can utilize it atJiminny, current limitations, etc.To be honest, I'm also fairly new to this, so I'll spendsome time this afternoon preparing myself.d 1Message #ai-chapter+...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
34473
|
1294
|
1
|
2026-05-13T11:17:38.817537+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778671058817_m2.jpg...
|
PhpStorm
|
faVsco.js – Sso.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhostormVIeWINavicarecodeLaravelKeractorFV faVsco. PhostormVIeWINavicarecodeLaravelKeractorFV faVsco.js?9 master kProiect© UpdateBotAvatar.pTeytRelayService.onpsso.onpxC) UodateTeamPhotosms-relay-failed.blade.phpSupport€ CheckTeamPlanEligibility.vD Jobs> @ Activity> @ AiAutomation0 AjReportsnamespace Jiminny Guards:use Auth0 Audiouse Jiminny Models User:v @ AutomatedReportsuse Jiminny Repositories (Userrepository:useuLuminate Suoport Facades LoosC) kequestGenerateASkJuse Suides Saml2 Events Sianedin:(C) kequestGeneratekepo© SendReportExpiringSo 10c) senckepor.ob.oho© SendReportMailJob.ph 11class SsoSendReportNotGenera 12>@ Calendarv D crmpublic function loginUser(Signedin Sevent): voidt...}Delete→ HuosootN Salesforce* Generate a redis key for token authentication provided a(C) AutoloaDelavedToCrm 44© CheckAndRetrvRemoti 56(C) CreateFollowuoActiviti 51* Qparam string Semail user email* Qparam string $token token without the 'jmny' partC) CreateNotes.oho(c) MatchActivitiecToNew(c) MatchActivitvCrmData 55public function getJiminnyTokenCacheKey(string Semail, string Stoken): string{...}© NoteObject.php© SaveActivity.php© SaveTranscription.php 60private tunction extracttma1urromAttributes(array sattributes): ?strinq"...(C) Setunl avout nhnl© SyncActivity.php© SyncFieldMetadata.ph© SyncHubspotObjects.r© SyncLeads.php© SyncObjects.php© SyncOpportunities.Job© SyncOpportunitv.php© SyncProfileMetadata.r© SyncTeamFieldsJob.plc) svncireamMetadata.ol© Undate@pportunitvSp(C) UodateStade.ohoDealRisksv 7 MailboxC) CreateBatches.ohoC) Createlnbox.oho9 DeleteFmailMescaaes(c) SmailTeytRelav nhn.(C) ProceccEmailsOnePas(C) Suneinhay nhnAccept File *~ X Reject File + * €€ 2 0f 2 files →> M MoptinaRot© MailboxController.php© SmsRelayFailed.phpRenect= custom.log|aravel.l0gA SF (jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X A console [EU]A console [STAGING] $66€661662663664669666 VTx: Auto vSo jiminnyAND to.domain = LOWERSUBSTRING INDEX(c.calendar provider id. '0'. -1)40 41 840 X.05GROUP BY t.id, t.name, calendar_domainORDER BY t.name.calendar domannselect * from users u join calendars c 1<->l.n: on c.user_id = u.idwhere u.tean id = 880select * from activities where id = 74049485; # team 563 crm 537select * from activities where id = 73272382; # team 563 crm 537select * from activities where id = 64400389; # team 563 crm 537select * from activities where id = 58081273; # team 563 crm 537select * from activities where id = 54520297; # team 563 crm 537select * from participants where activity id = 58081273:select * from activities where crm confiquration id = 537 and provider = 'aircalland account id = 19003658 order by updated at desc:select * from contacts where crm confiquration id = 537 and id = 35957759÷select * from accounts where erm confiquration id = 537 and id = 19003658:select * from automated report results where id = 1976:select * from automated_reports where id = 583;select * From activity searches where 10 = 87714:select * from activity search filters where activity search 1d = 877141SELECT * FROM activities WHERE uuid to bin('88274672-202d-4162-9d04-73f£5f0566a9') = uuidlor uuid to bind47842446-9f51-40ch-854f-cc6560290101" e uuid:SELECT * FROM crm_configurations WHERE provider = 'hubspot':select * from rate_limits;select * from autoand id IN (18, 1872);select * from automated_reports where id = 54;SELECT * FROM users WHERE id IN (24623,29443,29613):lated_report_results where media type = 'pdf' and status = 2SELECT * FROM automated_report_ results WHERE uuid to bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = vuid:select * from text relays where created at > '2026-05-01'# and id IN (32415, 32416);And ¿d - 20119.select * from users where team_id = 2 and email like '%scott%' and id = 29510suppont Dally • In 43h100% S2• Wed 13 May 14:17:38AskJiminnyReportActivityServiceTest vcascadeTrial Owner Role SeleSMS Fallure Emall.Error during tool execution >Searched User: where Emalllin app.Error durina tool execution ›Searched where. email.*= in appsearched user. emall in appThought for 1sкeас cmalllextkelay.onp #L300-319+0 ..wSearched User"where "emaill in annhought for 1sThought for 1s >Read UserRepositorv.pho #L350-369The UserRepository already has a findByEmail() method that checks both email and secondary email (lines 353-366 1' uodate EmailTextRelav. oho to use this repository method instead of the direct querv.Read FmailTeytRelav nhn #l 1-30.EmailTextRelav.ohoRead EmailTextRelay.php #L75-94Thought for 1c>• EmailTextRelay.php•EmailTextRelay.php+1-1Thouaht for 1s >Read Sso.phpC Sso.phpJ, 119 tokens* Reiect alliiAccent alliAsk anvthina 84L)O IDE error occurredSee details and suomit revort« Code SWF-1.6W Windsurf Teams7-1UTE.8io 4 spaces...
|
NULL
|
7808750014084994357
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhostormVIeWINavicarecodeLaravelKeractorFV faVsco. PhostormVIeWINavicarecodeLaravelKeractorFV faVsco.js?9 master kProiect© UpdateBotAvatar.pTeytRelayService.onpsso.onpxC) UodateTeamPhotosms-relay-failed.blade.phpSupport€ CheckTeamPlanEligibility.vD Jobs> @ Activity> @ AiAutomation0 AjReportsnamespace Jiminny Guards:use Auth0 Audiouse Jiminny Models User:v @ AutomatedReportsuse Jiminny Repositories (Userrepository:useuLuminate Suoport Facades LoosC) kequestGenerateASkJuse Suides Saml2 Events Sianedin:(C) kequestGeneratekepo© SendReportExpiringSo 10c) senckepor.ob.oho© SendReportMailJob.ph 11class SsoSendReportNotGenera 12>@ Calendarv D crmpublic function loginUser(Signedin Sevent): voidt...}Delete→ HuosootN Salesforce* Generate a redis key for token authentication provided a(C) AutoloaDelavedToCrm 44© CheckAndRetrvRemoti 56(C) CreateFollowuoActiviti 51* Qparam string Semail user email* Qparam string $token token without the 'jmny' partC) CreateNotes.oho(c) MatchActivitiecToNew(c) MatchActivitvCrmData 55public function getJiminnyTokenCacheKey(string Semail, string Stoken): string{...}© NoteObject.php© SaveActivity.php© SaveTranscription.php 60private tunction extracttma1urromAttributes(array sattributes): ?strinq"...(C) Setunl avout nhnl© SyncActivity.php© SyncFieldMetadata.ph© SyncHubspotObjects.r© SyncLeads.php© SyncObjects.php© SyncOpportunities.Job© SyncOpportunitv.php© SyncProfileMetadata.r© SyncTeamFieldsJob.plc) svncireamMetadata.ol© Undate@pportunitvSp(C) UodateStade.ohoDealRisksv 7 MailboxC) CreateBatches.ohoC) Createlnbox.oho9 DeleteFmailMescaaes(c) SmailTeytRelav nhn.(C) ProceccEmailsOnePas(C) Suneinhay nhnAccept File *~ X Reject File + * €€ 2 0f 2 files →> M MoptinaRot© MailboxController.php© SmsRelayFailed.phpRenect= custom.log|aravel.l0gA SF (jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X A console [EU]A console [STAGING] $66€661662663664669666 VTx: Auto vSo jiminnyAND to.domain = LOWERSUBSTRING INDEX(c.calendar provider id. '0'. -1)40 41 840 X.05GROUP BY t.id, t.name, calendar_domainORDER BY t.name.calendar domannselect * from users u join calendars c 1<->l.n: on c.user_id = u.idwhere u.tean id = 880select * from activities where id = 74049485; # team 563 crm 537select * from activities where id = 73272382; # team 563 crm 537select * from activities where id = 64400389; # team 563 crm 537select * from activities where id = 58081273; # team 563 crm 537select * from activities where id = 54520297; # team 563 crm 537select * from participants where activity id = 58081273:select * from activities where crm confiquration id = 537 and provider = 'aircalland account id = 19003658 order by updated at desc:select * from contacts where crm confiquration id = 537 and id = 35957759÷select * from accounts where erm confiquration id = 537 and id = 19003658:select * from automated report results where id = 1976:select * from automated_reports where id = 583;select * From activity searches where 10 = 87714:select * from activity search filters where activity search 1d = 877141SELECT * FROM activities WHERE uuid to bin('88274672-202d-4162-9d04-73f£5f0566a9') = uuidlor uuid to bind47842446-9f51-40ch-854f-cc6560290101" e uuid:SELECT * FROM crm_configurations WHERE provider = 'hubspot':select * from rate_limits;select * from autoand id IN (18, 1872);select * from automated_reports where id = 54;SELECT * FROM users WHERE id IN (24623,29443,29613):lated_report_results where media type = 'pdf' and status = 2SELECT * FROM automated_report_ results WHERE uuid to bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = vuid:select * from text relays where created at > '2026-05-01'# and id IN (32415, 32416);And ¿d - 20119.select * from users where team_id = 2 and email like '%scott%' and id = 29510suppont Dally • In 43h100% S2• Wed 13 May 14:17:38AskJiminnyReportActivityServiceTest vcascadeTrial Owner Role SeleSMS Fallure Emall.Error during tool execution >Searched User: where Emalllin app.Error durina tool execution ›Searched where. email.*= in appsearched user. emall in appThought for 1sкeас cmalllextkelay.onp #L300-319+0 ..wSearched User"where "emaill in annhought for 1sThought for 1s >Read UserRepositorv.pho #L350-369The UserRepository already has a findByEmail() method that checks both email and secondary email (lines 353-366 1' uodate EmailTextRelav. oho to use this repository method instead of the direct querv.Read FmailTeytRelav nhn #l 1-30.EmailTextRelav.ohoRead EmailTextRelay.php #L75-94Thought for 1c>• EmailTextRelay.php•EmailTextRelay.php+1-1Thouaht for 1s >Read Sso.phpC Sso.phpJ, 119 tokens* Reiect alliiAccent alliAsk anvthina 84L)O IDE error occurredSee details and suomit revort« Code SWF-1.6W Windsurf Teams7-1UTE.8io 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
34474
|
1294
|
2
|
2026-05-13T11:17:47.854885+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778671067854_m2.jpg...
|
PhpStorm
|
faVsco.js – Sso.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhostormVIeWINavicarecodeLaravelKeractorFV faVsco. PhostormVIeWINavicarecodeLaravelKeractorFV faVsco.js°9 master kroledey© MailboxController.php› D FormatsC) TextRelayService.onp© Sso.php X©TextMessagingService.phpsmskelayralled.pnpv D Guardssms-relay-failed.blade.php(C) TextRelay.phpc ViewerGuara.onp› D Helpersnamespace Jiminny Guards:Yш Huo> @ AccessTokenProviderv _ controllersuse Authv DAPIuse Jiminny Models User:› D AicallScorinause Jiminny Repositories \UserRepository:W AlReportsuse Illuminate Support \Facades\Log;use Suides Saml2 Events Sianedin:> DealinsiahtsOooortunitW PageScorecardsclass SsoN Settinas9 usagesN Teaminsiahtsnubiaie Function construct• M Themes• • UserAutomatedRep 15privare readonly UserRepository SuserRenositorvl(c) UcerAutomatedi 10© ActivityV2Contre 189) AckAnvthinaCor 19public function loginUser(SignedIn Sevent): void(C) Ack liminnvRena 26SsamlUser = $event->getSaml2UserO:(C) DealsV2Controll. 21Comanl = null.(e AnNamandvaec 240 DlevlictControlloSuser = User::where('email', $samlUser->getUserIdO)->firstO;© PlaylistShareCorPlavlistTrackCorSuser = Sthis->userRenositorv->findBvEmanSsamuUser->qetUserid00:c) Transcriptionsui// Fallback: try email from SAML attributes(c) UploadControlle© ActionItemsControl1f Suser === nulb <Log::info('[SSO] Trying to find user by email from SAML attributes', [ActivityController.D© AiCrmNotesControl"name id' => Ssamullisen->aetlsertdiorc)Basecontroller.ono€ ClientTokenControlSattrihutes = Ssamllisen->aetAttrihuteso•C) CrmController.ohoSemail= Sthis->extractEmas1FromAttrihutes(Sattrihutes):C) DealLevelPromotsclC)DealRiskController.nlC) InstantMeetinaConif (Semail |== null) {Susen = User::where('email' Semail)->first@:C) LanquadecontrolleC) LavoutManagemen' zcSuser = Sthis->userRepository->findByEmail($email{...}G LivefeedController. ca(C) MeetinasController caC) MescadeController. cz* Generate a redis keu for token authentication provided aC) MetadataController /(C) MobileSettinasCont ca* Qparam string Semail user emaiz© MomentController.f 56* Qparam string Stoken token without the 'imnu' partC0) NudaoControllor nh caa NumborAllonstore,") Arannizationl icons. co10 usadedpublic function getJimihnytokenca ~ Accept Fle xeX Pgiet Flping Stoken3® 3tsngt...an Arannizo.Renect= custom.log|aravel.l0gA SF (jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X A console [EU]A console [STAGING]D69.Tx: Auto v PlaygroundSo jiminnyAND to.domain = LOWERSUBSTRING INDEXc.calendar provider id. '0'. -1)040 A1 A40 V 65 ^GROUP BY t.id, t.name, calendar_domainORDER BY t.name, calendar domain:select * from users u join calendars c 1<->l.n: on c.user_id = u.idwhere u.tean id = 880select * from activities where id = 74049485• # team 563 crm 537select * from activities where id = 73272382; # team 563 crm 537select * from activities where id = 64400389; # team 563 crm 537select * from activities where id = 58081273; # team 563 crm 537select * from activities where id = 54520297; # team 563 crm 537select * from participants where activity id = 58081273:select * from activities where crm confiquration id = 537 and provider = 'aircalland account id = 19003658 order by updated at desc:select * from contacts where crm confiquration id = 537 and id = 35957759:select * from accounts where erm confiquration id = 537 and id = 19003658:select * from automated report results where id = 1976:select * from automated_reports where id = 583;select * From activity searches where 10 = 87714:select * from activity search filters where activity search_id = 87714:SELECT * FROM activities WHERE uuid to bin('88274672-202d-4162-9d04-73ff5f0566a9') = uuidon uuid to bin(:47842446-af51-4bch-854f-cc6560290101') = uuid:SELECT * FROM crm_configurations WHERE provider = 'hubspot' ;select * from rate_limits;select * from automated_report_results where media type = 'pdf' and status = 2and id IN (18, 1872);select * from automated_reports where id = 54;SELECT * SP0M ucenc WHERE id TN (24427 20443 20413)4SELECT * FROM automated_report_ results WHERE uuid to bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;666 Vselect * from text_relays where created_at > '2026-05-01)# and id IN (32415, 32416);And ¿d - 20119.select * from users where team_id = 2 and email like '%scott%' and id = 29510:suppont Dally • In 43h100% 2• Wed 13 May 14:17:47AskJiminnyReportActivityServiceTest vcascadeTrial Owner Role SeleSMS Fallure Emall.+0 ..Error during tool executionSearched where. email. = in appThoughtsSearched User"email in aoolRead EmailTextRelav.oho #L300-319Searched whereEmail in appwrroraltirinelolhlleyecttttonInougnttor is?Thouaht for 1s >Read UserRepository.php #L350-369Thouaht for 2c )The UserRepository already has a findByEmail() method that checks both email and secondary_email (lines 353-366 . lll update EmailTextRelay. php to use this repository method instead of the direct query.Read EmailTextRelav.pho #L1-30laatant threRead EmailTextRelay.php #L75-94EmailTextRelav.oho• EmailTextRelay.php+1-1Thought for 1s ›Thoughts• Sso.phrSso.nhnl+7-21Navigating•Reiect alllAccent alliAsk anvthina (84L)O IDE error occurredSee details and submit report« Code SWF-1.6W Windsurf Teams7-1UTE.8io 4 spaces...
|
NULL
|
-345810601534404796
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhostormVIeWINavicarecodeLaravelKeractorFV faVsco. PhostormVIeWINavicarecodeLaravelKeractorFV faVsco.js°9 master kroledey© MailboxController.php› D FormatsC) TextRelayService.onp© Sso.php X©TextMessagingService.phpsmskelayralled.pnpv D Guardssms-relay-failed.blade.php(C) TextRelay.phpc ViewerGuara.onp› D Helpersnamespace Jiminny Guards:Yш Huo> @ AccessTokenProviderv _ controllersuse Authv DAPIuse Jiminny Models User:› D AicallScorinause Jiminny Repositories \UserRepository:W AlReportsuse Illuminate Support \Facades\Log;use Suides Saml2 Events Sianedin:> DealinsiahtsOooortunitW PageScorecardsclass SsoN Settinas9 usagesN Teaminsiahtsnubiaie Function construct• M Themes• • UserAutomatedRep 15privare readonly UserRepository SuserRenositorvl(c) UcerAutomatedi 10© ActivityV2Contre 189) AckAnvthinaCor 19public function loginUser(SignedIn Sevent): void(C) Ack liminnvRena 26SsamlUser = $event->getSaml2UserO:(C) DealsV2Controll. 21Comanl = null.(e AnNamandvaec 240 DlevlictControlloSuser = User::where('email', $samlUser->getUserIdO)->firstO;© PlaylistShareCorPlavlistTrackCorSuser = Sthis->userRenositorv->findBvEmanSsamuUser->qetUserid00:c) Transcriptionsui// Fallback: try email from SAML attributes(c) UploadControlle© ActionItemsControl1f Suser === nulb <Log::info('[SSO] Trying to find user by email from SAML attributes', [ActivityController.D© AiCrmNotesControl"name id' => Ssamullisen->aetlsertdiorc)Basecontroller.ono€ ClientTokenControlSattrihutes = Ssamllisen->aetAttrihuteso•C) CrmController.ohoSemail= Sthis->extractEmas1FromAttrihutes(Sattrihutes):C) DealLevelPromotsclC)DealRiskController.nlC) InstantMeetinaConif (Semail |== null) {Susen = User::where('email' Semail)->first@:C) LanquadecontrolleC) LavoutManagemen' zcSuser = Sthis->userRepository->findByEmail($email{...}G LivefeedController. ca(C) MeetinasController caC) MescadeController. cz* Generate a redis keu for token authentication provided aC) MetadataController /(C) MobileSettinasCont ca* Qparam string Semail user emaiz© MomentController.f 56* Qparam string Stoken token without the 'imnu' partC0) NudaoControllor nh caa NumborAllonstore,") Arannizationl icons. co10 usadedpublic function getJimihnytokenca ~ Accept Fle xeX Pgiet Flping Stoken3® 3tsngt...an Arannizo.Renect= custom.log|aravel.l0gA SF (jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X A console [EU]A console [STAGING]D69.Tx: Auto v PlaygroundSo jiminnyAND to.domain = LOWERSUBSTRING INDEXc.calendar provider id. '0'. -1)040 A1 A40 V 65 ^GROUP BY t.id, t.name, calendar_domainORDER BY t.name, calendar domain:select * from users u join calendars c 1<->l.n: on c.user_id = u.idwhere u.tean id = 880select * from activities where id = 74049485• # team 563 crm 537select * from activities where id = 73272382; # team 563 crm 537select * from activities where id = 64400389; # team 563 crm 537select * from activities where id = 58081273; # team 563 crm 537select * from activities where id = 54520297; # team 563 crm 537select * from participants where activity id = 58081273:select * from activities where crm confiquration id = 537 and provider = 'aircalland account id = 19003658 order by updated at desc:select * from contacts where crm confiquration id = 537 and id = 35957759:select * from accounts where erm confiquration id = 537 and id = 19003658:select * from automated report results where id = 1976:select * from automated_reports where id = 583;select * From activity searches where 10 = 87714:select * from activity search filters where activity search_id = 87714:SELECT * FROM activities WHERE uuid to bin('88274672-202d-4162-9d04-73ff5f0566a9') = uuidon uuid to bin(:47842446-af51-4bch-854f-cc6560290101') = uuid:SELECT * FROM crm_configurations WHERE provider = 'hubspot' ;select * from rate_limits;select * from automated_report_results where media type = 'pdf' and status = 2and id IN (18, 1872);select * from automated_reports where id = 54;SELECT * SP0M ucenc WHERE id TN (24427 20443 20413)4SELECT * FROM automated_report_ results WHERE uuid to bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;666 Vselect * from text_relays where created_at > '2026-05-01)# and id IN (32415, 32416);And ¿d - 20119.select * from users where team_id = 2 and email like '%scott%' and id = 29510:suppont Dally • In 43h100% 2• Wed 13 May 14:17:47AskJiminnyReportActivityServiceTest vcascadeTrial Owner Role SeleSMS Fallure Emall.+0 ..Error during tool executionSearched where. email. = in appThoughtsSearched User"email in aoolRead EmailTextRelav.oho #L300-319Searched whereEmail in appwrroraltirinelolhlleyecttttonInougnttor is?Thouaht for 1s >Read UserRepository.php #L350-369Thouaht for 2c )The UserRepository already has a findByEmail() method that checks both email and secondary_email (lines 353-366 . lll update EmailTextRelay. php to use this repository method instead of the direct query.Read EmailTextRelav.pho #L1-30laatant threRead EmailTextRelay.php #L75-94EmailTextRelav.oho• EmailTextRelay.php+1-1Thought for 1s ›Thoughts• Sso.phrSso.nhnl+7-21Navigating•Reiect alllAccent alliAsk anvthina (84L)O IDE error occurredSee details and submit report« Code SWF-1.6W Windsurf Teams7-1UTE.8io 4 spaces...
|
34473
|
NULL
|
NULL
|
NULL
|
|
34475
|
1293
|
2
|
2026-05-13T11:17:59.475869+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778671079475_m1.jpg...
|
PhpStorm
|
faVsco.js – Sso.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
IDE error occurred
text/html
text/html
text/html
S IDE error occurred
text/html
text/html
text/html
See details and submit report
Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Jiminny\Repositories\UserRepository;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function __construct(
private readonly UserRepository $userRepository
) {
}
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = $this->userRepository->findByEmail($samlUser->getUserId());
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = $this->userRepository->findByEmail($email);
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['[URL_WITH_CREDENTIALS] -1)) AS calendar_domain
FROM teams t
JOIN users u ON u.team_id = t.id
JOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'
LEFT JOIN team_domains td
ON td.team_id = t.id
AND td.deleted_at IS NULL
AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))
GROUP BY t.id, t.name, calendar_domain
ORDER BY t.name, calendar_domain;
select * from users u join calendars c on c.user_id = u.id
where u.team_id = 882;
select * from activities where id = 74049485; # team 563 crm 537
select * from activities where id = 73272382; # team 563 crm 537
select * from activities where id = 64400389; # team 563 crm 537
select * from activities where id = 58081273; # team 563 crm 537
select * from activities where id = 54520297; # team 563 crm 537
select * from participants where activity_id = 58081273;
select * from activities where crm_configuration_id = 537 and provider = 'aircall'
and account_id = 19003658 order by updated_at desc;
select * from contacts where crm_configuration_id = 537 and id = 35957759;
select * from accounts where crm_configuration_id = 537 and id = 19003658;
select * from automated_report_results where id = 1976;
select * from automated_reports where id = 583;
select * from activity_searches where id = 87714;
select * from activity_search_filters where activity_search_id = 87714;
SELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid
or uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;
SELECT * FROM crm_configurations WHERE provider = 'hubspot';
select * from rate_limits;
select * from automated_report_results where media_type = 'pdf' and status = 2
and id IN (18, 1872);
select * from automated_reports where id = 54;
SELECT * FROM users WHERE id IN (24623,29443,29613);
SELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;
select * from text_relays where created_at > '2026-05-01'
# and id IN (32415, 32416);
and id = 32412;
select * from users where team_id = 2 and email like '%scott%' and id = 29510;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide
app ~/jiminny/app
.circleci
.cursor
.github
.sonarlint
.vscode
.windsurf
app, sources root
Actions
InviteUserToTeamAction.php, class...
|
[{"role":"AXTextField","text [{"role":"AXTextField","text":"IDE error occurred","depth":3,"on_screen":true,"value":"IDE error occurred","help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"text/html","depth":4,"on_screen":false,"help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"text/html","depth":4,"on_screen":true,"help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"text/html","depth":4,"on_screen":false,"help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXLink","text":"See details and submit report","depth":2,"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"on_screen":true,"help_text":"Git Branch: master<br/>Some incoming commits are not fetched<br/>","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\UserRepository;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function __construct(\n private readonly UserRepository $userRepository\n ) {\n }\n\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = $this->userRepository->findByEmail($samlUser->getUserId());\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = $this->userRepository->findByEmail($email);\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\UserRepository;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function __construct(\n private readonly UserRepository $userRepository\n ) {\n }\n\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = $this->userRepository->findByEmail($samlUser->getUserId());\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = $this->userRepository->findByEmail($email);\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\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":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":true,"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.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":"40","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"40","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"65","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 * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-05-01'\n# and id IN (32415, 32416);\nand id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;","depth":4,"on_screen":true,"value":"SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-05-01'\n# and id IN (32415, 32416);\nand id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"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":"InviteUserToTeamAction.php, class","depth":9,"on_screen":false,"role_description":"text"}]...
|
-9168218500848110326
|
2218600175241672261
|
idle
|
accessibility
|
NULL
|
IDE error occurred
text/html
text/html
text/html
S IDE error occurred
text/html
text/html
text/html
See details and submit report
Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Jiminny\Repositories\UserRepository;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function __construct(
private readonly UserRepository $userRepository
) {
}
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = $this->userRepository->findByEmail($samlUser->getUserId());
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = $this->userRepository->findByEmail($email);
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['[URL_WITH_CREDENTIALS] -1)) AS calendar_domain
FROM teams t
JOIN users u ON u.team_id = t.id
JOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'
LEFT JOIN team_domains td
ON td.team_id = t.id
AND td.deleted_at IS NULL
AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))
GROUP BY t.id, t.name, calendar_domain
ORDER BY t.name, calendar_domain;
select * from users u join calendars c on c.user_id = u.id
where u.team_id = 882;
select * from activities where id = 74049485; # team 563 crm 537
select * from activities where id = 73272382; # team 563 crm 537
select * from activities where id = 64400389; # team 563 crm 537
select * from activities where id = 58081273; # team 563 crm 537
select * from activities where id = 54520297; # team 563 crm 537
select * from participants where activity_id = 58081273;
select * from activities where crm_configuration_id = 537 and provider = 'aircall'
and account_id = 19003658 order by updated_at desc;
select * from contacts where crm_configuration_id = 537 and id = 35957759;
select * from accounts where crm_configuration_id = 537 and id = 19003658;
select * from automated_report_results where id = 1976;
select * from automated_reports where id = 583;
select * from activity_searches where id = 87714;
select * from activity_search_filters where activity_search_id = 87714;
SELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid
or uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;
SELECT * FROM crm_configurations WHERE provider = 'hubspot';
select * from rate_limits;
select * from automated_report_results where media_type = 'pdf' and status = 2
and id IN (18, 1872);
select * from automated_reports where id = 54;
SELECT * FROM users WHERE id IN (24623,29443,29613);
SELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;
select * from text_relays where created_at > '2026-05-01'
# and id IN (32415, 32416);
and id = 32412;
select * from users where team_id = 2 and email like '%scott%' and id = 29510;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide
app ~/jiminny/app
.circleci
.cursor
.github
.sonarlint
.vscode
.windsurf
app, sources root
Actions
InviteUserToTeamAction.php, class...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
34739
|
1300
|
20
|
2026-05-13T11:35:33.941997+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672133941_m2.jpg...
|
PhpStorm
|
faVsco.js – Sso.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Jiminny\Repositories\UserRepository;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function __construct(
private readonly UserRepository $userRepository
) {
}
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = $this->userRepository->findByEmail($samlUser->getUserId());
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = $this->userRepository->findByEmail($email);
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['[URL_WITH_CREDENTIALS] -1)) AS calendar_domain
FROM teams t
JOIN users u ON u.team_id = t.id
JOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'
LEFT JOIN team_domains td
ON td.team_id = t.id
AND td.deleted_at IS NULL
AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))
GROUP BY t.id, t.name, calendar_domain
ORDER BY t.name, calendar_domain;
select * from users u join calendars c on c.user_id = u.id
where u.team_id = 882;
select * from activities where id = 74049485; # team 563 crm 537
select * from activities where id = 73272382; # team 563 crm 537
select * from activities where id = 64400389; # team 563 crm 537
select * from activities where id = 58081273; # team 563 crm 537
select * from activities where id = 54520297; # team 563 crm 537
select * from participants where activity_id = 58081273;
select * from activities where crm_configuration_id = 537 and provider = 'aircall'
and account_id = 19003658 order by updated_at desc;
select * from contacts where crm_configuration_id = 537 and id = 35957759;
select * from accounts where crm_configuration_id = 537 and id = 19003658;
select * from automated_report_results where id = 1976;
select * from automated_reports where id = 583;
select * from activity_searches where id = 87714;
select * from activity_search_filters where activity_search_id = 87714;
SELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid
or uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;
SELECT * FROM crm_configurations WHERE provider = 'hubspot';
select * from rate_limits;
select * from automated_report_results where media_type = 'pdf' and status = 2
and id IN (18, 1872);
select * from automated_reports where id = 54;
SELECT * FROM users WHERE id IN (24623,29443,29613);
SELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;
select * from text_relays where created_at > '2026-05-01'
# and id IN (32415, 32416);
and id = 32412;
select * from users where team_id = 2 and email like '%scott%' and id = 29510;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JY-20891-improve-sms-text-relays, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.08843085,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: JY-20891-improve-sms-text-relays","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\UserRepository;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function __construct(\n private readonly UserRepository $userRepository\n ) {\n }\n\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = $this->userRepository->findByEmail($samlUser->getUserId());\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = $this->userRepository->findByEmail($email);\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\n }\n}","depth":4,"bounds":{"left":0.11402926,"top":0.14684756,"width":0.29587767,"height":0.85315245},"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\UserRepository;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function __construct(\n private readonly UserRepository $userRepository\n ) {\n }\n\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = $this->userRepository->findByEmail($samlUser->getUserId());\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = $this->userRepository->findByEmail($email);\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\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.40957448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.41821808,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.42918882,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43783244,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44647607,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.4574468,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46841756,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4950133,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.50598407,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.7084442,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"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":"40","depth":4,"bounds":{"left":0.67785907,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.69015956,"top":0.123703115,"width":0.00731383,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"40","depth":4,"bounds":{"left":0.6994681,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"65","depth":4,"bounds":{"left":0.7117686,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.7237367,"top":0.12210695,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.73105055,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-05-01'\n# and id IN (32415, 32416);\nand id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;","depth":4,"on_screen":true,"value":"SELECT * FROM teams WHERE name LIKE '%litify%'; # 1069, 994, 24993\nSELECT * FROM users WHERE id = 25061;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 994;\nSELECT * FROM crm_profiles WHERE user_id = 25061;\n\nselect * from crm_configurations where id = 834;\nSELECT * FROM teams WHERE id = 882;\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 = 882 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot' and crm_provider_id = 7270388;\n\nSELECT * FROM contacts where crm_configuration_id = 834;\nSELECT * FROM opportunities WHERE team_id = 933\n# AND crm_provider_id IN ('20131586060','46017317898','52543911090','53451356564','54101251892','54323768459');\nAND id IN (8482561,18352941,19042734,19232139,19445140,19472541);\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id IN (8482561,18352941,19042734,19232139,19445140,19472541);\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; #\nSELECT * FROM opportunities WHERE team_id = 933 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\nselect crm.provider, l.* from leads l join crm_configurations crm on l.crm_configuration_id = crm.id\nwhere crm.provider NOT IN ('salesforce', 'integration-app', 'bullhorn', 'copper')\n# and l.converted_at IS NOT NULL\n;\n\n# ********************************************************************\nSELECT * FROM activities a WHERE type IN ('email-inbound', 'email-outbound')\nand opportunity_id IS NULL\norder by id desc;\n\nSELECT * FROM teams WHERE id = 604; # 598\nSELECT * FROM activities WHERE id = 74410828; # chelseaw@allvoices.co\nSELECT * FROM accounts WHERE id = 20068382;\nSELECT * FROM accounts WHERE id = 35186038;\n\nSELECT * FROM contacts WHERE team_id = 852 and updated_at > '2026-01-23 12:30:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 559 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('cb6342b6-a183-401c-b0af-ede92b2ae763') = uuid;\nselect * from sidekick_settings where team_id = 781;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 26651871; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 7562435;\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8420347; # opflit 2100\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 711;\nSELECT * FROM activities where crm_configuration_id = 711 and crm_provider_id IS NULL\nand is_internal = 0 and status = 'completed'\norder by id desc;\n\nSELECT * FROM crm_layout_entities\nWHERE crm_layout_id IN (2352, 2353);\n;\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and id = 530;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 556 and sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('c6ca4b22-7738-4563-a95d-b8a9598924ae') = uuid;\nSELECT * FROM activities WHERE uuid_to_bin('442abb2b-28bd-4be8-9c25-19e9bf02766d') = uuid;\nselect * from contacts\nwhere crm_configuration_id = 530\nand crm_provider_id = 872252;\n\nselect * from activities where crm_configuration_id = 530\nand user_id = 14343 and type like '%softphone%'\nand created_at between '2026-01-28 15:00:00' and '2026-01-28 15:10:00';\n\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 25666868; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id = 8646335; # Teya\nSELECT * FROM crm_configurations where provider = 'hubspot' and crm_provider_id IN (5933397);\n\n\nSELECT t.name, t.id, t.owner_id, c.id, c.provider, c.crm_base_url FROM teams t\nJOIN crm_configurations c ON t.id = c.team_id\nWHERE t.status = 'active';\n\nSELECT * FROM teams where id = 1091;\nSELECT * FROM crm_configurations where team_id = 1091;\nSELECT * FROM activity_providers where team_id = 1091;\nSELECT * FROM activities where crm_configuration_id = 1024 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT * FROM teams WHERE name LIKE '%Leadventure%';\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 = 1091 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%Wilson%'; # 862, 812\nSELECT * FROM teams where id = 862;\nSELECT * FROM crm_configurations where team_id = 862;\nSELECT * FROM activity_providers where team_id = 862;\nSELECT * FROM activities where crm_configuration_id = 812 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\n\n\nSELECT t.id, crm.id, crm.provider, ap.* FROM teams t\njoin crm_configurations crm on t.id = crm.team_id\njoin activity_providers ap on t.id = ap.team_id\nwhere t.status = 'active' and ap.is_enabled = 1\nand crm.provider = 'hubspot'\nand ap.provider NOT IN ('hubspot', 'aircall', 'uploader', 'gong', 'twilio', 'zoom-bot', 'google-meet', 'ms-teams',\n 'outreach', 'close', 'ringcentral', 'dialpad', 'zoom-phone');\n\nSELECT * FROM teams where id = 1068;\nSELECT * FROM crm_configurations where team_id = 1068;\nSELECT * FROM activity_providers where team_id = 1068;\n\nSELECT * FROM activities a\nwhere crm_configuration_id = 993 and type IN ('softphone', 'softphone-outbound')\nand a.provider NOT IN ('hubspot', 'uploader', 'gong', 'twilio', 'google-meet', 'ms-teams','close'\n )\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by a.id desc;\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1068 and sa.provider = 'hubspot';\n\n# ********************************************************************\n# ********************************************************************\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 882; # 933 - GoGlobal , portalId: 6017093\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 933 and updated_at > '2026-02-06 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 933 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 834; # 882 - AnyVan , portalId: 5468262\nSELECT * FROM contacts WHERE crm_configuration_id = 834 and updated_at > '2026-03-30 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and updated_at > '2026-03-04 08:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 882 and sa.provider = 'hubspot';\nselect * from crm_layouts where crm_configuration_id = 834;\nselect * from crm_layout_entities where crm_layout_id = 2780;\nselect * from crm_fields where id IN (321153,321192,321193,321194);\n\nSELECT * FROM opportunities WHERE crm_configuration_id = 834 and id = 10993426;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 988; # 1057 - Teya (543ce4f4-168c-4571-91ea-5b35c253f06f) , portalId: 26651871\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1057 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1057 and sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations where id = 533; # 559 - Connectd , portalId: 6710988\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 559 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 801; # 852 - Rise Vision , portalId: 2700250\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 852 and updated_at > '2026-02-04 00:00:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 962; # 1034 - evergrowth.io , portalId: 143180990\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1034 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 1037; # 1102 - Jibble , portalId: 6649755\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1102 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 8\n\nSELECT * FROM crm_configurations where id = 1015; # 1049 - Travefy , portalId: 48904401\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1049 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 20\n\nSELECT * FROM crm_configurations where id = 64; # 70 - SalaryFinance , portalId: 3404115\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 70 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 6th last\n\nSELECT * FROM crm_configurations where id = 802; # 853 - Street Group , portalId: 7658438\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 853 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 10\n\nSELECT * FROM crm_configurations where id = 872; # 921 - In Professional Development , portalId: 9238273\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 921 and updated_at > '2026-02-04 12:30:00' order by updated_at desc; # 2\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 550; # 576 - SeedLegals , portalId: 3028661\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 576 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 989; # 1058 - rtaoutdoor.com , portalId: 22371204\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1058 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 896; # 946 - Mintago , portalId: 6621281\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 946 and updated_at > '2026-02-05 14:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 617; # 641 - PCS , portalId: 5244937\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 641 and updated_at > '2026-02-05 14:00:00' order by updated_at desc; # 7th\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 649; # 670 - Eventeny , portalId: 4492849\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-18 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 670 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; #\n\nSELECT * FROM crm_configurations where id = 48; # 51 - CleanCloud , portalId: 4373137\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-03-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 51 and updated_at > '2026-02-09 08:00:00' order by updated_at desc;\nselect * from users where team_id = 51; # 7783\nSELECT * FROM groups WHERE uuid_to_bin('8a8d2cb6-8b55-4fa3-8b5c-5f0e3d8de59a') = uuid; # 1130\nselect * from activity_searches where user_id = 7783;\nselect * from activity_search_filters where activity_search_id IN (32291, 32292);\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations where id = 272; # 290 - Bonham & Brook , portalId: 5705856\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-05 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 290 and updated_at > '2026-02-09 08:00:00' order by updated_at desc; # 6th\n# ********************************************************************\nSELECT * FROM crm_configurations where provider = 'hubspot';\nSELECT * FROM crm_configurations where id = 1056; # 1119 - Chromatic , portalId: 45602133\nSELECT * FROM opportunities WHERE team_id = 1119 and remotely_created_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 1119 and updated_at > '2026-02-09 09:00:00' order by updated_at desc; # null\n# ********************************************************************\n\nselect * from contacts where crm_provider_id = '003Uu00000ojD4NIAU';\nselect\n cp.*\n# DISTINCT t.id\n# cp.id, cp.user_id, t.id, cp.crm_configuration_id, cp.contact_fields\nFROM crm_profiles cp\nJOIN crm_configurations crm on crm.id = cp.crm_configuration_id\nJOIN users u on u.id = cp.user_id\nJOIN teams t ON t.id = crm.team_id\nWHERE crm.provider = 'salesforce' and t.status = 'active'\n and cp.archived_at IS NULL and u.deleted_at IS NULL\n and t.id NOT IN (1093)\n and t.id = 2\n and cp.contact_fields IS NULL;\n# and c.crm_provider_id = '003Uu00000ojD4NIAU';\n\nSELECT * FROM users WHERE id = 26484;\nSELECT * FROM crm_profiles WHERE user_id = 26484;\nSELECT * FROM social_accounts WHERE sociable_id = 26484;\nSELECT * FROM crm_configurations where provider = 'salesforce';\nselect * from users where id IN (10022, 10403);\nselect * from users where team_id IN (526);\nselect * from teams where id IN (526, 532);\nselect * from crm_configurations where id IN (500, 516);\nselect * from crm_profiles where crm_configuration_id IN (500, 516) and user_id IN (10022, 10403);\nselect * from contacts where crm_configuration_id IN (500, 516) and crm_provider_id = '003Uu00000ojD4NIAU';\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 = 526 and sa.provider = 'salesforce';\nselect * from team_settings where team_id IN (526, 532);\n\nselect * from users where id IN (22824);\nselect * from crm_profiles where crm_configuration_id IN (1026);\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1093 and sa.provider = 'salesforce';\n\nselect * from teams where id = 1099;\nselect * from users where id = 29643\n\nselect * from activity_processing_states;\n\nSELECT * FROM teams where name LIKE '%Fare%'; # 233\nSELECT * FROM opportunities where crm_configuration_id = 215\n# and crm_provider_id = 'oppo_ogESZf2P50nDrd1nGPvKDXeA6sSaTN5v51Lp4ayVzKR'\n;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1088 and sa.provider = 'hubspot';\n\nSELECT * FROM teams order by updated_at DESC\nSELECT * FROM crm_configurations WHERE id = 1019; # SimpleConsign 1088 - no social account\n\nselect * from crm_configurations where provider = 'pipedrive';\n\nselect * from teams where id = 957;\nselect * from crm_configurations where id = 957;\n\nSELECT * FROM teams WHERE name LIKE '%Prolific%'; # 544, 518, 10743\nSELECT * FROM opportunities where crm_configuration_id = 518 order by id desc;\n\nselect * from users where team_id = 1; # 26726 - Gabriela Dureva\nSELECT * FROM opportunities where user_id = 26726; # 16834447 - Prolific\nselect * from activities where user_id = 26726 order by id desc;\nselect * from contacts where crm_configuration_id = 1\nand email IN ('charlotte.ward@prolific.com', 'frankie.bryant@prolific.com'); # 2094416, 2093620\nSELECT * FROM contacts WHERE id = 6284931;\n\nSELECT p.* FROM activities a JOIN participants p ON a.id = p.activity_id\nWHERE a.user_id = 26726 and p.lead_id IN (2094416, 2093620) and a.created_at > '2026-01-01 00:00:00' order by p.email;\n\nselect * from activities where id IN (75509259,75509261,75509261,75511034,75026464,75517602,75517605);\nselect * from crm_configurations where id = 1;\n\n43801692-1aeb-32ce-acba-5b80a479701a\n44c3c9cf-6f5e-75f3-8179-bc9f75dd2b1b\n405975c0-b3d0-7aaa-821f-09d59cae6dd1\n4caf848d-4bed-2299-b248-7788d41f9fca\n49bedc3f-f196-eef3-89c3-dea6a3b4aa63\n43420989-a09d-b8f8-9806-c8bbf7a02aac\n\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1 and sa.provider = 'salesforce';\n\nSELECT * FROM activities WHERE id = 75461988;\n\nSELECT * FROM activities WHERE uuid_to_bin('d6c5052e-e972-49e9-8912-26f2f7d6c5f6') = uuid;\n\nselect * from contacts where id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nselect * from users where id = 21047;\nSELECT * FROM crm_configurations WHERE id = 892;\nSELECT * FROM teams WHERE id = 942;\nselect * from opportunities where team_id = 942 order by updated_at desc;\nselect * from contacts where team_id = 942 order by updated_at desc;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 942 and sa.provider = 'hubspot';\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id IN ('006Pq00000NeH6XIAV', '006Pq000007z8kdIAA'); # 10697889, 6621430\nSELECT * FROM crm_configurations WHERE id = 1;\nSELECT * FROM teams WHERE crm_id = 1;\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 = 1 and sa.provider = 'salesforce';\n\nselect id, user_id, opportunity_fields from crm_profiles where crm_configuration_id = 1\nSELECT * FROM opportunities where team_id = 1 order by updated_at desc; # 10697889, 6621430\n\nselect * from teams where id = 852;\nselect * from groups where id = 2286;\nselect * from sidekick_settings where team_id = 852;\nselect * from default_activity_types where team_id = 852;\n\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id AND p.id IS NULL -- no profile\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active' -- team is active\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1 AND u.deleted_at IS NULL\nAND u.crm_required = 1\nAND u.team_id = 1\nORDER BY u.team_id;\n\nSELECT * FROM crm_profiles cp where cp.crm_configuration_id = 1 and cp.user_id IN (\n18481\n );\n\nSELECT cc.provider, cc.id, p.id, u.*\nFROM users u\nLEFT JOIN crm_profiles p ON u.id = p.user_id\nINNER JOIN teams t ON u.team_id = t.id AND t.status = 'active'\nINNER JOIN crm_configurations cc ON t.crm_id = cc.id\nWHERE u.status = 1\n AND u.deleted_at IS NULL\n AND u.crm_required = 1\n# AND u.team_id = 1\n AND p.id IS NULL -- Move this condition to WHERE clause\nORDER BY u.team_id;\n\nSELECT * FROM opportunities WHERE id = 20002609;\nselect * from teams where id = 1122; # Velatir, 29953 - christian@velatir.com\nselect * from crm_configurations where id = 1060;\nselect * from crm_layouts where crm_configuration_id = 1060;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3596;\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 = 1122 and sa.provider = 'hubspot';\nselect * from opportunities where team_id = 1122 order by updated_at desc;\n\nselect * from crm_field_data where object_type = 'contact';\n\nSELECT * FROM activities WHERE uuid_to_bin('374fc8ed-3315-4c9f-9b25-318b7fd2928f') = uuid; # 76584262\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 = 248 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles where user_id = 24115; # 005QF000002CswMYAS\nSELECT * FROM users where id = 24115;\nSELECT * FROM accounts where id = 4002896;\nSELECT * FROM teams WHERE name LIKE '%adswerve%';\nSELECT * FROM opportunities where crm_configuration_id = 230 AND crm_provider_id IN (\"0069N000003GIQ9QAO\",\"0061r000019yGP9AAM\",\"0066900001S2KWlAAN\",\"0066900001TDpj2AAD\",\"0066900001b8uEwAAI\",\"0069N000001rQi0QAE\",\"006QF00000KD40mYAD\",\"006QF00000LzpRJYAZ\",\"0069N000002uomtQAA\",\"0069N000002xlMLQAY\",\"0066900001NV6ubAAD\",\"0061r00001HJp45AAD\",\"006QF00000uTlUoYAK\",\"006QF00000v0bZqYAI\");\nSELECT * FROM opportunities WHERE crm_configuration_id = 230 AND crm_provider_id = '0069N000003GIQ9QAO'; # 6272203\n\nSELECT u.id, u.email, ac.name, a.* FROM activities a\nJOIN users u ON a.user_id = u.id\nJOIN accounts ac ON a.account_id = ac.id\nWHERE\nuuid_to_bin('e3269598-b562-44fb-b5e9-9d2694dc63e0') = a.uuid or\nuuid_to_bin('66ddc3ab-4e15-45aa-af0c-248c1eece593') = a.uuid or\nuuid_to_bin('826bd328-e1cc-4213-b8d8-572454cacc07') = a.uuid;\n\nselect * from users where id = 5825;\nSELECT * FROM activities WHERE uuid_to_bin('e56aa2e8-231a-421b-ab1f-cb38ed2bf573') = uuid;\n\nselect * from activities where uuid_to_bin('91e13b2f-2d1b-45f8-b1fd-1141b6563782') = uuid;\n19594, 862\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 = 862 and sa.provider = 'salesforce';\n\nselect * from automated_reports where id = 36;\nselect ar.frequency, r.*, ar.* from automated_report_results r\njoin automated_reports ar on r.report_id = ar.id\nwhere ar.frequency != 'one_off';\n\nselect s.* from activity_searches s join users u ON s.user_id = u.id where u.team_id = 882;\nselect * from nudges n where n.activity_search_id\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 1065; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 3617;\n\nselect * from users where team_id = 1 and name like '%Lukas%'; # 7160\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\nSELECT * FROM teams WHERE name LIKE '%Integrum ESG%'; # 1126, 1065,\nselect * from opportunities where team_id = 1126;\nSELECT * FROM teams WHERE name LIKE '%Base%'; # 1125, 1063,\nselect * from opportunities where team_id = 1125;\nselect * from contacts c\nwhere c.team_id = 882;\n\nSELECT * FROM activities WHERE id = 76822967;\nSELECT * FROM crm_profiles WHERE user_id = 15440;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 555;\nSELECT * FROM crm_configurations WHERE id = 555;\nSELECT * FROM users WHERE id = 15440; # team. 581, gr. 15440, pl. 3911, act. field 162182\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 = 581 and sa.provider = 'salesforce';\n\nSELECT * FROM automated_report_results order by id desc;\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556;\n\nselect * from automated_reports;\nwhere id = 54; # 4fdd41f6-dcf0-30d0-b339-7345381b6044 , [\"pdf\",\"podcast\"]\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\nselect * from automated_report_results order by id desc;\nSELECT * FROM automated_report_results WHERE id = 1919;\n\nselect * from automated_report_results WHERE report_id = 54;\n\nselect * from opportunities where id = 7594349;\n\nSELECT * FROM teams WHERE name LIKE '%Les%'; # 711, 692, 16067 - jiminnyintegration@lesmills.com\nselect * from playbooks where team_id = 711; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 5515;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 692 and object_type = 'event';\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 692;\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 = 711 and sa.provider = 'salesforce';\n\nSELECT * FROM crm_profiles cp JOIN users u on u.id = cp.user_id WHERE u.team_id = 711;\n\nselect * from leads;\n\nselect * from calendars;\n\nSELECT\n t.id AS team_id,\n t.name,\n LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1)) AS calendar_domain\nFROM teams t\nJOIN users u ON u.team_id = t.id\nJOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'\nLEFT JOIN team_domains td\n ON td.team_id = t.id\n AND td.deleted_at IS NULL\n AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))\nGROUP BY t.id, t.name, calendar_domain\nORDER BY t.name, calendar_domain;\n\nselect * from users u join calendars c on c.user_id = u.id\nwhere u.team_id = 882;\n\n\nselect * from activities where id = 74049485; # team 563 crm 537\nselect * from activities where id = 73272382; # team 563 crm 537\nselect * from activities where id = 64400389; # team 563 crm 537\nselect * from activities where id = 58081273; # team 563 crm 537\nselect * from activities where id = 54520297; # team 563 crm 537\nselect * from participants where activity_id = 58081273;\n\nselect * from activities where crm_configuration_id = 537 and provider = 'aircall'\nand account_id = 19003658 order by updated_at desc;\n\nselect * from contacts where crm_configuration_id = 537 and id = 35957759;\nselect * from accounts where crm_configuration_id = 537 and id = 19003658;\n\nselect * from automated_report_results where id = 1976;\nselect * from automated_reports where id = 583;\nselect * from activity_searches where id = 87714;\nselect * from activity_search_filters where activity_search_id = 87714;\n\nSELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid\nor uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;\n\nSELECT * FROM crm_configurations WHERE provider = 'hubspot';\nselect * from rate_limits;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2\nand id IN (18, 1872);\nselect * from automated_reports where id = 54;\nSELECT * FROM users WHERE id IN (24623,29443,29613);\n\nSELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;\n\nselect * from text_relays where created_at > '2026-05-01'\n# and id IN (32415, 32416);\nand id = 32412;\n\nselect * from users where team_id = 2 and email like '%scott%' and id = 29510;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3038570400826649895
|
1065678670634825285
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Jiminny\Repositories\UserRepository;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function __construct(
private readonly UserRepository $userRepository
) {
}
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = $this->userRepository->findByEmail($samlUser->getUserId());
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = $this->userRepository->findByEmail($email);
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['[URL_WITH_CREDENTIALS] -1)) AS calendar_domain
FROM teams t
JOIN users u ON u.team_id = t.id
JOIN calendars c ON c.user_id = u.id AND c.status = 'active' AND c.calendar_provider_id LIKE '%@%'
LEFT JOIN team_domains td
ON td.team_id = t.id
AND td.deleted_at IS NULL
AND td.domain = LOWER(SUBSTRING_INDEX(c.calendar_provider_id, '@', -1))
GROUP BY t.id, t.name, calendar_domain
ORDER BY t.name, calendar_domain;
select * from users u join calendars c on c.user_id = u.id
where u.team_id = 882;
select * from activities where id = 74049485; # team 563 crm 537
select * from activities where id = 73272382; # team 563 crm 537
select * from activities where id = 64400389; # team 563 crm 537
select * from activities where id = 58081273; # team 563 crm 537
select * from activities where id = 54520297; # team 563 crm 537
select * from participants where activity_id = 58081273;
select * from activities where crm_configuration_id = 537 and provider = 'aircall'
and account_id = 19003658 order by updated_at desc;
select * from contacts where crm_configuration_id = 537 and id = 35957759;
select * from accounts where crm_configuration_id = 537 and id = 19003658;
select * from automated_report_results where id = 1976;
select * from automated_reports where id = 583;
select * from activity_searches where id = 87714;
select * from activity_search_filters where activity_search_id = 87714;
SELECT * FROM activities WHERE uuid_to_bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuid
or uuid_to_bin('47842446-af51-4bcb-854f-cc6560290101') = uuid;
SELECT * FROM crm_configurations WHERE provider = 'hubspot';
select * from rate_limits;
select * from automated_report_results where media_type = 'pdf' and status = 2
and id IN (18, 1872);
select * from automated_reports where id = 54;
SELECT * FROM users WHERE id IN (24623,29443,29613);
SELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;
select * from text_relays where created_at > '2026-05-01'
# and id IN (32415, 32416);
and id = 32412;
select * from users where team_id = 2 and email like '%scott%' and id = 29510;
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
34740
|
1299
|
17
|
2026-05-13T11:35:34.746541+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672134746_m1.jpg...
|
PhpStorm
|
faVsco.js – Sso.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = User::where('email', $samlUser->getUserId())->first();
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = User::where('email', $email)->first();
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]
?? $attributes['Email'][0]
?? $attributes['mail'][0]
?? null;
}
}
Execute
Explain Plan...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JY-20891-improve-sms-text-relays, menu","depth":5,"on_screen":true,"help_text":"Git Branch: JY-20891-improve-sms-text-relays","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = User::where('email', $samlUser->getUserId())->first();\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = User::where('email', $email)->first();\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = User::where('email', $samlUser->getUserId())->first();\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = User::where('email', $email)->first();\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\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}]...
|
7107178179960359548
|
-4177829598284273274
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = User::where('email', $samlUser->getUserId())->first();
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = User::where('email', $email)->first();
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]
?? $attributes['Email'][0]
?? $attributes['mail'][0]
?? null;
}
}
Execute
Explain Plan...
|
34737
|
NULL
|
NULL
|
NULL
|
|
34741
|
1300
|
21
|
2026-05-13T11:35:34.746601+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672134746_m2.jpg...
|
PhpStorm
|
faVsco.js – Sso.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = User::where('email', $samlUser->getUserId())->first();
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = User::where('email', $email)->first();
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]
?? $attributes['Email'][0]
?? $attributes['mail'][0]
?? null;
}
}...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JY-20891-improve-sms-text-relays, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.08843085,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: JY-20891-improve-sms-text-relays","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = User::where('email', $samlUser->getUserId())->first();\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = User::where('email', $email)->first();\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\n }\n}","depth":4,"bounds":{"left":0.11968085,"top":0.14684756,"width":0.28823137,"height":0.85315245},"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Guards;\n\nuse Auth;\nuse Jiminny\\Models\\User;\nuse Illuminate\\Support\\Facades\\Log;\nuse Slides\\Saml2\\Events\\SignedIn;\n\nclass Sso\n{\n public function loginUser(SignedIn $event): void\n {\n $samlUser = $event->getSaml2User();\n $email = null;\n\n $user = User::where('email', $samlUser->getUserId())->first();\n\n // Fallback: try email from SAML attributes\n if ($user === null) {\n Log::info('[SSO] Trying to find user by email from SAML attributes', [\n 'name_id' => $samlUser->getUserId(),\n ]);\n\n $attributes = $samlUser->getAttributes();\n $email = $this->extractEmailFromAttributes($attributes);\n\n if ($email !== null) {\n $user = User::where('email', $email)->first();\n }\n }\n\n if ($user === null || $user->status !== User::STATUS_ACTIVE) {\n Log::warning('[SSO] Login failed', [\n 'name_id' => $samlUser->getUserId(),\n 'email_used' => $email,\n 'reason' => $user === null ? 'user_not_found' : 'user_inactive',\n ]);\n\n return;\n }\n\n Auth::login($user);\n }\n\n /**\n * Generate a redis key for token authentication provided a\n *\n * @param string $email user email\n * @param string $token token without the 'jmny' part\n */\n public function getJiminnyTokenCacheKey(string $email, string $token): string\n {\n $hash = hash('sha256', $email . $token);\n\n return 'auth-token-' . $hash;\n }\n\n private function extractEmailFromAttributes(array $attributes): ?string\n {\n return $attributes['email'][0]\n ?? $attributes['emailAddress'][0]\n ?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]\n ?? $attributes['Email'][0]\n ?? $attributes['mail'][0]\n ?? null;\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false}]...
|
1745443977687139676
|
-4177831797307528954
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
namespace Jiminny\Guards;
use Auth;
use Jiminny\Models\User;
use Illuminate\Support\Facades\Log;
use Slides\Saml2\Events\SignedIn;
class Sso
{
public function loginUser(SignedIn $event): void
{
$samlUser = $event->getSaml2User();
$email = null;
$user = User::where('email', $samlUser->getUserId())->first();
// Fallback: try email from SAML attributes
if ($user === null) {
Log::info('[SSO] Trying to find user by email from SAML attributes', [
'name_id' => $samlUser->getUserId(),
]);
$attributes = $samlUser->getAttributes();
$email = $this->extractEmailFromAttributes($attributes);
if ($email !== null) {
$user = User::where('email', $email)->first();
}
}
if ($user === null || $user->status !== User::STATUS_ACTIVE) {
Log::warning('[SSO] Login failed', [
'name_id' => $samlUser->getUserId(),
'email_used' => $email,
'reason' => $user === null ? 'user_not_found' : 'user_inactive',
]);
return;
}
Auth::login($user);
}
/**
* Generate a redis key for token authentication provided a
*
* @param string $email user email
* @param string $token token without the 'jmny' part
*/
public function getJiminnyTokenCacheKey(string $email, string $token): string
{
$hash = hash('sha256', $email . $token);
return 'auth-token-' . $hash;
}
private function extractEmailFromAttributes(array $attributes): ?string
{
return $attributes['email'][0]
?? $attributes['emailAddress'][0]
?? $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'][0]
?? $attributes['Email'][0]
?? $attributes['mail'][0]
?? null;
}
}...
|
34739
|
NULL
|
NULL
|
NULL
|
|
34476
|
1294
|
3
|
2026-05-13T11:18:06.099906+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778671086099_m2.jpg...
|
PhpStorm
|
faVsco.js – SsoController.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
IDE error occurred
text/html
text/html
text/html
S IDE error occurred
text/html
text/html
text/html
See details and submit report
Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings...
|
[{"role":"AXTextField","text [{"role":"AXTextField","text":"IDE error occurred","depth":3,"bounds":{"left":0.8753325,"top":0.92577815,"width":0.11037234,"height":0.013567438},"on_screen":true,"value":"IDE error occurred","help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"text/html","depth":4,"on_screen":false,"help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"text/html","depth":4,"bounds":{"left":0.8753325,"top":0.92577815,"width":0.03756649,"height":0.013567438},"on_screen":true,"help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"text/html","depth":4,"on_screen":false,"help_text":"text/html","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXLink","text":"See details and submit report","depth":2,"bounds":{"left":0.8753325,"top":0.943336,"width":0.06017287,"height":0.013567438},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"master, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.040226065,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: master<br/>Some incoming commits are not fetched<br/>","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-2198012054923100996
|
-8348531133650851385
|
visual_change
|
hybrid
|
NULL
|
IDE error occurred
text/html
text/html
text/html
S IDE error occurred
text/html
text/html
text/html
See details and submit report
Project: faVsco.js, menu
master, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
PhostormINavicareCodeLaravelKeractorWindowFV faVsco.js?9 master kProiect(C) InviteUserToTeamAction.ohn(C) UserinvitationD lo.ong© MailboxController.php• m ScorecardsC) TextRelavService.ong© SsoController.php XTextmessagingservice.ong• D Settingssms-relay-failed.blade.php© SmsLength.phpTeaminsights• M Themecv D UserAutomatedRep(C) UcerAutomated!vDv2© ActivityV2Contrcnamespace Jiminny Http Controulers APIS© AskAnythingCor(C) AsKJiminnykepouseuuuminate Htto usonResponse:© DealsV2Controlluse uminate Hito Request:use Jiminny Comoonent Saml2 FederationMetadata:c) OnDemanavzec€ PlavlistControlleuse Jiminny Htto Responses Aoi Resoonse.€ PlavlistShareCor 11use Jiminny Models User:€ PlavlistTrackCor 12use Jiminny RepAccept Reject(C) TranscriotionSur 10use Suides Saml2 Models Tenant.© UploadControlle 14use Symfony \Component \HttpFoundation\Response as SymfonyResponse:© Action|temsControl 150 ActivitvController.n 16class Scolontrollen eytends RaseContnollenC) AlcrmNotescontrol 1/C) BaseController.oho 18C) ClientTokenControl 14C) CrmController.oho© DealLevelPromotsC 21 © ;public function __construct(Response $response){...}C) DealRiskController.1 21(c) InctantMeptinaCont 2dc) LanquadeControllet* Return the SSO login URL given user emaiz© LayoutManagemen 30€ LiveFeedController(C) MeetinasController 3112,public function ssoLogin(Request Srequest): JsonResponse{...}C) MeccadeController 67e) MotadataControllarC Mahilo CottinacCant@) MamontControllor r 72€ NudgeController.ph 784) NumborAllnantore,OrganizationLicensOrganizationMembc) OrganizationRetentc) OrganizationRolesec) OrcanizationsvnceP PartnerController.oC) PhoneNumberContP PlavbackController@ PlavlistController.ol@ ScimController.ohp@ SidekickController.9a) SoftnhoneControlli(C) SubscrintionGontro(C) ToamAiAutomationAccept File *~ X Reject File + * €< 3 of 3 files →= custom.log|aravel.l0gA SF (jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X A console [EU]A console [STAGING] €661662663664669666 VTx: Auto vAND to.domain = LOWERSUBSTRING INDEXc.calendar provider id. '0'. -1)GROUP BY t.id, t.name, calendar_domainORDER BY t.name, calendar domain:select * from users u join calendars c 1<->l.n: on c.user_id = u.idwhere u.tean id = 880select * from activities where id = 74049485; # team 563 crm 537select * from activities where id = 73272382; # team 563 crm 537select * from activities where id = 64400389; # team 563 crm 537select * from activities where id = 58081273; # team 563 crm 537select * from activities where id = 54520297; # team 563 crm 537select * from participants where activity id = 58081273:select * from activities where crm_confiquration id = 537 and provider = 'aircall)and account id = 19003658 order by updated at desc:select * from contacts where crm confiquration id = 537 and id = 35957759÷select * from accounts where erm confiquration id = 537 and id = 19003658:select * from automated report results where id = 1976:select * from automated_reports where id = 583;select * from activity searches where id = 87714:select * from activity search filters where activity search_id = 87714:SELECT * FROM activities WHERE uuid to bin('88274672-202d-4162-9d04-73f£5f0566a9') = uuidlon uuid to bin(:47842446-af51-4bch-854f-cc6560290101') = uuid:SFLECT * FROM com configurations WHERE provider = 'hubspot':select * from nate Limits:select * from autoand id IN (18, 1872);select * from automated_reports where id = 54;SELECT * FROM users WHERE id IN (24623,29443,29613):lated_report_results where media type = 'pdf' and status = 2SELECT * FROM automated_report_ results WHERE uuid to bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;select * from text_relays where created_at > '2026-05-01)# and id IN (32415, 32416);And ¿d - 20119.select * from users where team id = 2 and email like '%scott%' and id = 29510)So jiminny040 A1 A40 V 65 ^suppont Dally • In 42m100% S2• Wed 13 May 14:18:06AskJiminnyReportActivityServiceTest vcascadeTrial Owner Role SeleSMS Fallure Emall.+0 ..Thought for 1swRead Emalllextkelay.php #L300-319inougneror 1s>Searched where-mall in appError durina tool executionSearched User*where "email in aoolCoarched findRvEmail in ann/ModeldThe UserRepository already has a findByEmail() method that checks both email and secondary email (lines 353-366). I'll update EmailTextRelay- php to use this repository method instead of the direct query.Read EmailTextRelay.php #L1-30Thouaht for 1s EmailTeytRelav.ohnThoughtsRead EmailTextRelav.pho #L75-94• EmailTextRelay.php+1-1" EmailTextRelav.php+1-1Thoucht for 1s >kead sso.onpThouahts• Sso.phpThoughts• Sso.php+7-2ThoughtsRead SsoController.ohrL SsoController.ohvAsk anvthina (84L)« Code SWF-1.6* Reiect alliiO IDE error occurredSee details and submit reportWN Windsurf Teams12-1UITE.8IAccent alliio 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
34721
|
1300
|
9
|
2026-05-13T11:35:02.076368+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672102076_m2.jpg...
|
PhpStorm
|
faVsco.js – SsoController.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
declare(strict_types=1);
namespace Jiminny\Http\Controllers\API;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jiminny\Component\Saml2\FederationMetadata;
use Jiminny\Http\Responses\Api\Response;
use Jiminny\Models\User;
use Jiminny\Repositories\UserRepository;
use Slides\Saml2\Models\Tenant;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class SsoController extends BaseController
{
/**
* Create a new controller instance.
*/
public function __construct(Response $response, UserRepository $userRepository)
{
parent::__construct($response);
$this->response = $response;
$this->userRepository = $userRepository;
}
/**
* Return the SSO login URL given user email
*/
public function ssoLogin(Request $request): JsonResponse
{
$user = $this->userRepository->findByEmail($request->email);
if (! $user instanceof User) {
return $this->responseErrorNotFound();
}
$tenant = $user->getTeam()->getTenant();
if (! $tenant instanceof Tenant) {
return $this->responseErrorNotFound();
}
// Schedule async refresh of Azure federation metadata XML (if needed)
$metadata = app()->make(FederationMetadata::class);
$metadata->refreshMetadataAsyncIfNeeded($tenant);
$redirectUrl = $request->get('redirect');
$useTokenAuth = $request->get('tokenAuth');
$loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');
if (! empty($useTokenAuth)) {
$itineraryUrl = route('login.token');
if (! empty($redirectUrl)) {
$itineraryUrl .= '?returnTo=' . $redirectUrl;
}
$itineraryUrl = urlencode($itineraryUrl);
$loginUrl .= '?returnTo=' . $itineraryUrl;
}
return response()->json([
'login_url' => $loginUrl,
]);
}
private function responseErrorNotFound(): JsonResponse
{
return response()->json([
'errors' => [
'not-found',
],
'message' => "Sorry, we can't find your account. Please contact Support if you need further assistance",
], SymfonyResponse::HTTP_NOT_FOUND);
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JY-20891-improve-sms-text-relays, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.08843085,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: JY-20891-improve-sms-text-relays","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Http\\Controllers\\API;\n\nuse Illuminate\\Http\\JsonResponse;\nuse Illuminate\\Http\\Request;\nuse Jiminny\\Component\\Saml2\\FederationMetadata;\nuse Jiminny\\Http\\Responses\\Api\\Response;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\UserRepository;\nuse Slides\\Saml2\\Models\\Tenant;\nuse Symfony\\Component\\HttpFoundation\\Response as SymfonyResponse;\n\nclass SsoController extends BaseController\n{\n /**\n * Create a new controller instance.\n */\n public function __construct(Response $response, UserRepository $userRepository)\n {\n parent::__construct($response);\n\n $this->response = $response;\n $this->userRepository = $userRepository;\n }\n\n /**\n * Return the SSO login URL given user email\n */\n public function ssoLogin(Request $request): JsonResponse\n {\n $user = $this->userRepository->findByEmail($request->email);\n\n if (! $user instanceof User) {\n return $this->responseErrorNotFound();\n }\n\n $tenant = $user->getTeam()->getTenant();\n if (! $tenant instanceof Tenant) {\n return $this->responseErrorNotFound();\n }\n\n // Schedule async refresh of Azure federation metadata XML (if needed)\n $metadata = app()->make(FederationMetadata::class);\n $metadata->refreshMetadataAsyncIfNeeded($tenant);\n\n $redirectUrl = $request->get('redirect');\n $useTokenAuth = $request->get('tokenAuth');\n\n $loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');\n\n if (! empty($useTokenAuth)) {\n $itineraryUrl = route('login.token');\n if (! empty($redirectUrl)) {\n $itineraryUrl .= '?returnTo=' . $redirectUrl;\n }\n $itineraryUrl = urlencode($itineraryUrl);\n\n $loginUrl .= '?returnTo=' . $itineraryUrl;\n }\n\n return response()->json([\n 'login_url' => $loginUrl,\n ]);\n }\n\n private function responseErrorNotFound(): JsonResponse\n {\n return response()->json([\n 'errors' => [\n 'not-found',\n ],\n 'message' => \"Sorry, we can't find your account. Please contact Support if you need further assistance\",\n ], SymfonyResponse::HTTP_NOT_FOUND);\n }\n}","depth":4,"bounds":{"left":0.11968085,"top":0.14684756,"width":0.29587767,"height":0.8324022},"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Http\\Controllers\\API;\n\nuse Illuminate\\Http\\JsonResponse;\nuse Illuminate\\Http\\Request;\nuse Jiminny\\Component\\Saml2\\FederationMetadata;\nuse Jiminny\\Http\\Responses\\Api\\Response;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\UserRepository;\nuse Slides\\Saml2\\Models\\Tenant;\nuse Symfony\\Component\\HttpFoundation\\Response as SymfonyResponse;\n\nclass SsoController extends BaseController\n{\n /**\n * Create a new controller instance.\n */\n public function __construct(Response $response, UserRepository $userRepository)\n {\n parent::__construct($response);\n\n $this->response = $response;\n $this->userRepository = $userRepository;\n }\n\n /**\n * Return the SSO login URL given user email\n */\n public function ssoLogin(Request $request): JsonResponse\n {\n $user = $this->userRepository->findByEmail($request->email);\n\n if (! $user instanceof User) {\n return $this->responseErrorNotFound();\n }\n\n $tenant = $user->getTeam()->getTenant();\n if (! $tenant instanceof Tenant) {\n return $this->responseErrorNotFound();\n }\n\n // Schedule async refresh of Azure federation metadata XML (if needed)\n $metadata = app()->make(FederationMetadata::class);\n $metadata->refreshMetadataAsyncIfNeeded($tenant);\n\n $redirectUrl = $request->get('redirect');\n $useTokenAuth = $request->get('tokenAuth');\n\n $loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');\n\n if (! empty($useTokenAuth)) {\n $itineraryUrl = route('login.token');\n if (! empty($redirectUrl)) {\n $itineraryUrl .= '?returnTo=' . $redirectUrl;\n }\n $itineraryUrl = urlencode($itineraryUrl);\n\n $loginUrl .= '?returnTo=' . $itineraryUrl;\n }\n\n return response()->json([\n 'login_url' => $loginUrl,\n ]);\n }\n\n private function responseErrorNotFound(): JsonResponse\n {\n return response()->json([\n 'errors' => [\n 'not-found',\n ],\n 'message' => \"Sorry, we can't find your account. Please contact Support if you need further assistance\",\n ], SymfonyResponse::HTTP_NOT_FOUND);\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.40957448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.41821808,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.42918882,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43783244,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44647607,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.4574468,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46841756,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4950133,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-189265562461466434
|
-8430512446449142189
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
<?php
declare(strict_types=1);
namespace Jiminny\Http\Controllers\API;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jiminny\Component\Saml2\FederationMetadata;
use Jiminny\Http\Responses\Api\Response;
use Jiminny\Models\User;
use Jiminny\Repositories\UserRepository;
use Slides\Saml2\Models\Tenant;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class SsoController extends BaseController
{
/**
* Create a new controller instance.
*/
public function __construct(Response $response, UserRepository $userRepository)
{
parent::__construct($response);
$this->response = $response;
$this->userRepository = $userRepository;
}
/**
* Return the SSO login URL given user email
*/
public function ssoLogin(Request $request): JsonResponse
{
$user = $this->userRepository->findByEmail($request->email);
if (! $user instanceof User) {
return $this->responseErrorNotFound();
}
$tenant = $user->getTeam()->getTenant();
if (! $tenant instanceof Tenant) {
return $this->responseErrorNotFound();
}
// Schedule async refresh of Azure federation metadata XML (if needed)
$metadata = app()->make(FederationMetadata::class);
$metadata->refreshMetadataAsyncIfNeeded($tenant);
$redirectUrl = $request->get('redirect');
$useTokenAuth = $request->get('tokenAuth');
$loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');
if (! empty($useTokenAuth)) {
$itineraryUrl = route('login.token');
if (! empty($redirectUrl)) {
$itineraryUrl .= '?returnTo=' . $redirectUrl;
}
$itineraryUrl = urlencode($itineraryUrl);
$loginUrl .= '?returnTo=' . $itineraryUrl;
}
return response()->json([
'login_url' => $loginUrl,
]);
}
private function responseErrorNotFound(): JsonResponse
{
return response()->json([
'errors' => [
'not-found',
],
'message' => "Sorry, we can't find your account. Please contact Support if you need further assistance",
], SymfonyResponse::HTTP_NOT_FOUND);
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements...
|
34720
|
NULL
|
NULL
|
NULL
|
|
34722
|
1299
|
10
|
2026-05-13T11:35:03.348325+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672103348_m1.jpg...
|
PhpStorm
|
faVsco.js – SsoController.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
iTerm2ShellEditViewSessionScripts|ProfilesWindowHe iTerm2ShellEditViewSessionScripts|ProfilesWindowHelpAPP (-zsh)APP (-zsh)> 083(allSupport Daily - in 25 mADOCKERDEV (docker)882-zshdelete mode 100644 app/Component/ES/Worker/WorkerAmount.phpdelete mode 100644 app/Component/ES/Worker/WorkerInterface.phpcreate mode 100644 app/Component/ProphetAi/Exceptions/InsufficientTranscriptException.phpcreate mode 100644 app/Component/Transcription/DTO/Http/Transcription/AssemblyAI/AssemblyAI/NoAssemblyIdException.phpcreate mode 100644 app/Component/Transcription/DTO/Http/Transcription/TranscriptionIsNotCorrectFormatException.phpcreate mode100644app/Console/Commands/Crm/Backfill0pportunityUserFromAccountCommand.phpdelete mode100644 app/Console/Commands/Elasticsearch/AsyncUpdateEsActivities.phpcreate mode 100644 front-end/src/components/shared/modals/EntityPickerModal/__tests__/useEntitiesCache.spec.tscreate mode 100644 tests/Feature/Component/Nudge/ProcessOrganisationImmediateNudgesJobTest.phpcreate mode 100644 tests/Unit/Component/AiAutomation/Services/CrmFillingEligibilityCheckerTest.phpdelete mode 100644 tests/Unit/Component/ES/ElasticSearchWorkerManagerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/ActivityWorkerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/EntityWorkerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/WorkerAmountTest.phpcreate mode 100644 tests/Unit/Component/ParticipantSpeech/Services/ParticipantSpeechesCreatorTest.phpcreatemode 100644 tests/Unit/Http/Controllers/Kiosk/ActivityControllerTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (master) $ git pullremote:Enumerating objects: 29,done.remote: Counting objects: 100% (29/29), done.remote: Compressing objects: 100% (20/20), done.remote: Total 29 (delta 14), reused 11 (delta 9), pack-reused 0 (from 0)Unpacking objects: 100% (29/29), 16.36 KiB | 644.00 KiB/s, done.From github.com:jiminny/appObfd964b74..3893b9772cmaster-> origin/master4f960247ed..4fe0405141JY-20820-es-reindex-stream-model-hydration -> origin/JY-20820-es-reindex-stream-model-hydration1ff6f70f48..62a7fe6277remove-phpstan-errors-> origin/remove-phpstan-errorsUpdating 0bfd964b74..3893b9772cFast-forwardapp/Component/Encoding/Job/AnalyzeTrackChannelsJob.phpapp/Component/FFMpeg/Services/GetSpeechIntervalsService.phpapp/Console/Commands/Activities/SetupIntegration/TwilioSetS3RecordingCredentialsCommand.php201894app/Console/Kernel.phpapp/Jobs/ImportRemoteTrackJob.phpapp/Services/Activity/Twilio/S3RecordingCredentialsService.phptests/Feature/Jobs/ImportRemoteTrackJobTest.phptests/Unit/Component/Encoding/Job/AnalyzeTrackChannelsJobTest.phptests/Unit/Component/FFMpeg/Services/GetSpeechIntervalsTest.phptests/Unit/Services/Activity/Twilio/S3RecordingCredentialsServiceTest.php7882285523618010 files changed, 823 insertions(+), 23 deletions(-)create mode 100644 app/Console/Commands/Activities/SetupIntegration/TwilioSetS3RecordingCredentialsCommand.phpcreate mode 100644 app/Services/Activity/Twilio/S3RecordingCredentialsService.phpcreate mode 100644 tests/Unit/Services/Activity/Twilio/S3RecordingCredentialsServiceTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (master) $ co -b JY-20891-improve-sms-text-relaysSwitched to a new branch 'JY-20891-improve-sms-text-relays'lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20891-improve-sms-text-relays) $ |||84100% С8• Wed 13 May 14:35:03181screenpipe"О ₴5APP...
|
NULL
|
-7862400763891556353
|
NULL
|
click
|
ocr
|
NULL
|
iTerm2ShellEditViewSessionScripts|ProfilesWindowHe iTerm2ShellEditViewSessionScripts|ProfilesWindowHelpAPP (-zsh)APP (-zsh)> 083(allSupport Daily - in 25 mADOCKERDEV (docker)882-zshdelete mode 100644 app/Component/ES/Worker/WorkerAmount.phpdelete mode 100644 app/Component/ES/Worker/WorkerInterface.phpcreate mode 100644 app/Component/ProphetAi/Exceptions/InsufficientTranscriptException.phpcreate mode 100644 app/Component/Transcription/DTO/Http/Transcription/AssemblyAI/AssemblyAI/NoAssemblyIdException.phpcreate mode 100644 app/Component/Transcription/DTO/Http/Transcription/TranscriptionIsNotCorrectFormatException.phpcreate mode100644app/Console/Commands/Crm/Backfill0pportunityUserFromAccountCommand.phpdelete mode100644 app/Console/Commands/Elasticsearch/AsyncUpdateEsActivities.phpcreate mode 100644 front-end/src/components/shared/modals/EntityPickerModal/__tests__/useEntitiesCache.spec.tscreate mode 100644 tests/Feature/Component/Nudge/ProcessOrganisationImmediateNudgesJobTest.phpcreate mode 100644 tests/Unit/Component/AiAutomation/Services/CrmFillingEligibilityCheckerTest.phpdelete mode 100644 tests/Unit/Component/ES/ElasticSearchWorkerManagerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/ActivityWorkerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/EntityWorkerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/WorkerAmountTest.phpcreate mode 100644 tests/Unit/Component/ParticipantSpeech/Services/ParticipantSpeechesCreatorTest.phpcreatemode 100644 tests/Unit/Http/Controllers/Kiosk/ActivityControllerTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (master) $ git pullremote:Enumerating objects: 29,done.remote: Counting objects: 100% (29/29), done.remote: Compressing objects: 100% (20/20), done.remote: Total 29 (delta 14), reused 11 (delta 9), pack-reused 0 (from 0)Unpacking objects: 100% (29/29), 16.36 KiB | 644.00 KiB/s, done.From github.com:jiminny/appObfd964b74..3893b9772cmaster-> origin/master4f960247ed..4fe0405141JY-20820-es-reindex-stream-model-hydration -> origin/JY-20820-es-reindex-stream-model-hydration1ff6f70f48..62a7fe6277remove-phpstan-errors-> origin/remove-phpstan-errorsUpdating 0bfd964b74..3893b9772cFast-forwardapp/Component/Encoding/Job/AnalyzeTrackChannelsJob.phpapp/Component/FFMpeg/Services/GetSpeechIntervalsService.phpapp/Console/Commands/Activities/SetupIntegration/TwilioSetS3RecordingCredentialsCommand.php201894app/Console/Kernel.phpapp/Jobs/ImportRemoteTrackJob.phpapp/Services/Activity/Twilio/S3RecordingCredentialsService.phptests/Feature/Jobs/ImportRemoteTrackJobTest.phptests/Unit/Component/Encoding/Job/AnalyzeTrackChannelsJobTest.phptests/Unit/Component/FFMpeg/Services/GetSpeechIntervalsTest.phptests/Unit/Services/Activity/Twilio/S3RecordingCredentialsServiceTest.php7882285523618010 files changed, 823 insertions(+), 23 deletions(-)create mode 100644 app/Console/Commands/Activities/SetupIntegration/TwilioSetS3RecordingCredentialsCommand.phpcreate mode 100644 app/Services/Activity/Twilio/S3RecordingCredentialsService.phpcreate mode 100644 tests/Unit/Services/Activity/Twilio/S3RecordingCredentialsServiceTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (master) $ co -b JY-20891-improve-sms-text-relaysSwitched to a new branch 'JY-20891-improve-sms-text-relays'lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20891-improve-sms-text-relays) $ |||84100% С8• Wed 13 May 14:35:03181screenpipe"О ₴5APP...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
34723
|
1300
|
10
|
2026-05-13T11:35:03.347099+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672103347_m2.jpg...
|
PhpStorm
|
faVsco.js – SsoController.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhostormVIewINavicarecodeLaravelKeractorWindowFV f PhostormVIewINavicarecodeLaravelKeractorWindowFV faVsco.js°9 JY-20891-improve-sms-text-relaysroledey(C) InviteUserToTeamAction.ohn© MailboxController.phpSidekickController.plSoftphoneControllerTextkelayservice.phpe suoscriptioncontroll© TeamAiAutomationCsms-relay-failed.blade.php© SmsLength.phpk?php) leamAicontexiconuTeamController.phpdeclare(strict_ types=1)C) Teaminsichtscontrolc) Transcriptioncontrolnamesoace Jaminny Htto controulers APi:c) Translationcontroller© UserController.phpc) VocabularvcontrolleluseIluminate Htto sonResponse:use ILuminate Htto Reauest•AUthuse Jiminny Comoonent Saml2 FederationMetadata:© ConfirmPasswordCol 1g© ExtensionController.f 11© ForgotPasswordCont 1% IntearationController 13use Jiminny Htto Resoonses Ani Resoonse:use aiminny Modes lisen:use Jiminny Repositories\UserRepository:luse SlidesSaml2 Models Tenant.C) LodinController.ohouse Symfony\Component\HttpFoundation\Response as SymfonyResponse;g) OnboardController.pl 15© RegisterController.pt© ResetPasswordContr ^7(c) SocialController.phpclass SsoController extends BaseControllerc) SsoController.pnp) M CustomerAnilMinternalnublic function construct(Response Sresponse)v D Kiosk>D Teams© ActivityController.phi 21( AutomatedReportsC, 2921 ot>public function construct(Response Sresponse. UserRepository SuserRepository){...}lC) DashboardController 30* Return the SS0 Zogin URL aiven user emai© ImpersonationContrc 31© MediaPipelineControOrganizationsContro 32 4>PartnersController.pt 68*/G-Tlaoivllauth/sso/loain ssoll.oainlnublic function ssoloain(Request Srequest): IsonResponsef.?c) Protillecontroller.ono© SearchController.phr 69v MSettinas> MCoachindprivate function responseErrorNotFound: JsonResponset...}• Profilev Teams> D Billing> D UtilsC) IntearationContro(C) InvitationControll.C) OraanizationSetti(C) TeamActivitvContC) TeamCoachingSeYa) TonmController n(6) ToamNonlincichte(e) ToamNomaincCorT 1 of4 editsAccept File *~ X Reject File + * €< 2 of 4 files →Reiect all chandec in this fileRejectnatauite confiliatca Clone Caret Relow.andilimore_shottaut.confliatwith.mac0SichortautsModifivthese chattaits.orchande.mac0S/svstem.sattinas.//lMadifv.Shodtalitc//lDonitShowAaain./12.minutes.aan• suppont Dally • In zom100% S2• Wed 13 May 14:35:02AskJiminnyReportActivityServiceTest v= custom.log|aravel.l0gA SF (jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X A console [EU]cascadeA console [STAGING]63063263363S6456476486526536546551— 656658659660669664Trial Owner Role SeleRetactoring User EmaTx: Auto vSo jiminnyI need only EmailTextRelay? | changed it a bit. REveiw itAND td.domain = LOWERSUBSTRINGLNDEX(c.calendar provider 1d,'d', -1)0GROUP BY t.id, t.name, calendar domain040 A1 A40 V 65 ^OrDER BY t.name.select * from users u join calendars c 1<->1..n: on c.user id = u.idwhere u.team id = 882select * from activities where id = 14049485: # team 563 crm 537select * from activities where id = 73272382; # team 563 crm 537select * from activities where id = 64400389; # team 563 crm 537select * from activities where id = 58081273; # team 563 crm 537select * from activities whene id = 54520207• # +eam 563 crm 537select * from participants where activity_id = 58081273;select * from activities where crm_configuration_id = 537 and provider = 'aircalland account_id = 19003658 order by updated_at desc:select * from contacts where crm_configuration_id = 537 and id = 35957759;select * from accounts where crm confiquration id = 537 and id = 19003658:select * from automated report results where id = 1976:select * from automated_reports where id = 583;select * from activity searches whereid = 87714;select * from activity search_filters where activity search_id = 87714:SELECT * FROM activities WHERE uuid to bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuidor uuid to bin(•47842446-af51-4bcb-854f-cc6560290101') = uuid:SELECT * FROM crm configurations WHERE provider = 'hubspot'.select * from rate limitsated_report_results where media type = 'pdf' and status = 2and id IN (18, 1872);select * fromautomated_reports where id = 54;SELECT * FROM users WHERE id IN (24623,29443,29613):Read EmailTextRelay.phpTnoughttor 2s>Your changes to EmailTextRelay.php look good:Changes Made:1. Multi-line method signature (lines 80-84) - Follows coding standards for better readability2. Pass SuserRepository to checkIntegrity (line 107) - Keeps dependency injection focused3. Updated checkintegrity signature (line 251) - Now accepts UserRepository SuserRepository4. Undated user lookun (line 308) - Chanaed from User::where("emaj]" Ssender)-sfirct() to SuserRenositorv->fiReview:wulserReSitorv: :findBvEmailo checks both emaii and cecondarv email fieldsThe dependency injection is cleaner - UserRepository is only used where needed•V Folllows the codina standards (multi- ine method sianatures• • No breaking changes to the existing logicThis approach is actually better than mine - vou kept the UserRepository usage localized to checkintearity where theucor lookun sctually hannens rather than ucina it in bandle and naccina the ticer aroundiThe fix will resolve Scott's issue if he adds rewardgateway.com as his secondary_email in Jiminny. The SMS relay will nowtind his account when he sends from that email adaress.lo Il «.SELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;665666 V667select * from text_relays where created_at > '2026-05-01'# and id IN (32415, 32416);and id = 20112.select * from users where team id = 2 and email like '%scott%' and id = 29510ollers/API D SsoController.php +4 -2anniGunrdel M Sco nhn 48 .2ann/l isteners/Users/M ValidateSendinaMescaae.nhn 16 -3s/M SxternalldUniaueToHostValidationRule.ohvAsk anvthina (84L)« Code SWF-1.6Reiect alllAccent alliWN Windsurf TeamsUTE..io 4 spaces...
|
NULL
|
-966376449207210245
|
NULL
|
click
|
ocr
|
NULL
|
PhostormVIewINavicarecodeLaravelKeractorWindowFV f PhostormVIewINavicarecodeLaravelKeractorWindowFV faVsco.js°9 JY-20891-improve-sms-text-relaysroledey(C) InviteUserToTeamAction.ohn© MailboxController.phpSidekickController.plSoftphoneControllerTextkelayservice.phpe suoscriptioncontroll© TeamAiAutomationCsms-relay-failed.blade.php© SmsLength.phpk?php) leamAicontexiconuTeamController.phpdeclare(strict_ types=1)C) Teaminsichtscontrolc) Transcriptioncontrolnamesoace Jaminny Htto controulers APi:c) Translationcontroller© UserController.phpc) VocabularvcontrolleluseIluminate Htto sonResponse:use ILuminate Htto Reauest•AUthuse Jiminny Comoonent Saml2 FederationMetadata:© ConfirmPasswordCol 1g© ExtensionController.f 11© ForgotPasswordCont 1% IntearationController 13use Jiminny Htto Resoonses Ani Resoonse:use aiminny Modes lisen:use Jiminny Repositories\UserRepository:luse SlidesSaml2 Models Tenant.C) LodinController.ohouse Symfony\Component\HttpFoundation\Response as SymfonyResponse;g) OnboardController.pl 15© RegisterController.pt© ResetPasswordContr ^7(c) SocialController.phpclass SsoController extends BaseControllerc) SsoController.pnp) M CustomerAnilMinternalnublic function construct(Response Sresponse)v D Kiosk>D Teams© ActivityController.phi 21( AutomatedReportsC, 2921 ot>public function construct(Response Sresponse. UserRepository SuserRepository){...}lC) DashboardController 30* Return the SS0 Zogin URL aiven user emai© ImpersonationContrc 31© MediaPipelineControOrganizationsContro 32 4>PartnersController.pt 68*/G-Tlaoivllauth/sso/loain ssoll.oainlnublic function ssoloain(Request Srequest): IsonResponsef.?c) Protillecontroller.ono© SearchController.phr 69v MSettinas> MCoachindprivate function responseErrorNotFound: JsonResponset...}• Profilev Teams> D Billing> D UtilsC) IntearationContro(C) InvitationControll.C) OraanizationSetti(C) TeamActivitvContC) TeamCoachingSeYa) TonmController n(6) ToamNonlincichte(e) ToamNomaincCorT 1 of4 editsAccept File *~ X Reject File + * €< 2 of 4 files →Reiect all chandec in this fileRejectnatauite confiliatca Clone Caret Relow.andilimore_shottaut.confliatwith.mac0SichortautsModifivthese chattaits.orchande.mac0S/svstem.sattinas.//lMadifv.Shodtalitc//lDonitShowAaain./12.minutes.aan• suppont Dally • In zom100% S2• Wed 13 May 14:35:02AskJiminnyReportActivityServiceTest v= custom.log|aravel.l0gA SF (jiminny@localhost]4 HS_local [jiminny@localhost]& console (PROD] X A console [EU]cascadeA console [STAGING]63063263363S6456476486526536546551— 656658659660669664Trial Owner Role SeleRetactoring User EmaTx: Auto vSo jiminnyI need only EmailTextRelay? | changed it a bit. REveiw itAND td.domain = LOWERSUBSTRINGLNDEX(c.calendar provider 1d,'d', -1)0GROUP BY t.id, t.name, calendar domain040 A1 A40 V 65 ^OrDER BY t.name.select * from users u join calendars c 1<->1..n: on c.user id = u.idwhere u.team id = 882select * from activities where id = 14049485: # team 563 crm 537select * from activities where id = 73272382; # team 563 crm 537select * from activities where id = 64400389; # team 563 crm 537select * from activities where id = 58081273; # team 563 crm 537select * from activities whene id = 54520207• # +eam 563 crm 537select * from participants where activity_id = 58081273;select * from activities where crm_configuration_id = 537 and provider = 'aircalland account_id = 19003658 order by updated_at desc:select * from contacts where crm_configuration_id = 537 and id = 35957759;select * from accounts where crm confiquration id = 537 and id = 19003658:select * from automated report results where id = 1976:select * from automated_reports where id = 583;select * from activity searches whereid = 87714;select * from activity search_filters where activity search_id = 87714:SELECT * FROM activities WHERE uuid to bin('8827f672-202d-4162-9d04-73ff5f0566a9') = uuidor uuid to bin(•47842446-af51-4bcb-854f-cc6560290101') = uuid:SELECT * FROM crm configurations WHERE provider = 'hubspot'.select * from rate limitsated_report_results where media type = 'pdf' and status = 2and id IN (18, 1872);select * fromautomated_reports where id = 54;SELECT * FROM users WHERE id IN (24623,29443,29613):Read EmailTextRelay.phpTnoughttor 2s>Your changes to EmailTextRelay.php look good:Changes Made:1. Multi-line method signature (lines 80-84) - Follows coding standards for better readability2. Pass SuserRepository to checkIntegrity (line 107) - Keeps dependency injection focused3. Updated checkintegrity signature (line 251) - Now accepts UserRepository SuserRepository4. Undated user lookun (line 308) - Chanaed from User::where("emaj]" Ssender)-sfirct() to SuserRenositorv->fiReview:wulserReSitorv: :findBvEmailo checks both emaii and cecondarv email fieldsThe dependency injection is cleaner - UserRepository is only used where needed•V Folllows the codina standards (multi- ine method sianatures• • No breaking changes to the existing logicThis approach is actually better than mine - vou kept the UserRepository usage localized to checkintearity where theucor lookun sctually hannens rather than ucina it in bandle and naccina the ticer aroundiThe fix will resolve Scott's issue if he adds rewardgateway.com as his secondary_email in Jiminny. The SMS relay will nowtind his account when he sends from that email adaress.lo Il «.SELECT * FROM automated_report_results WHERE uuid_to_bin('822fa41b-afd3-43a9-a248-86b0e36f3131') = uuid;665666 V667select * from text_relays where created_at > '2026-05-01'# and id IN (32415, 32416);and id = 20112.select * from users where team id = 2 and email like '%scott%' and id = 29510ollers/API D SsoController.php +4 -2anniGunrdel M Sco nhn 48 .2ann/l isteners/Users/M ValidateSendinaMescaae.nhn 16 -3s/M SxternalldUniaueToHostValidationRule.ohvAsk anvthina (84L)« Code SWF-1.6Reiect alllAccent alliWN Windsurf TeamsUTE..io 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
34724
|
1300
|
11
|
2026-05-13T11:35:07.101245+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672107101_m2.jpg...
|
PhpStorm
|
faVsco.js – SsoController.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
3
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Http\Controllers\API;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jiminny\Component\Saml2\FederationMetadata;
use Jiminny\Http\Responses\Api\Response;
use Jiminny\Models\User;
use Slides\Saml2\Models\Tenant;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class SsoController extends BaseController
{
/**
* Create a new controller instance.
*/
public function __construct(Response $response)
{
parent::__construct($response);
$this->response = $response;
}
/**
* Return the SSO login URL given user email
*/
public function ssoLogin(Request $request): JsonResponse
{
$user = User::where('email', $request->email)->first();
if (! $user instanceof User) {
return $this->responseErrorNotFound();
}
$tenant = $user->getTeam()->getTenant();
if (! $tenant instanceof Tenant) {
return $this->responseErrorNotFound();
}
// Schedule async refresh of Azure federation metadata XML (if needed)
$metadata = app()->make(FederationMetadata::class);
$metadata->refreshMetadataAsyncIfNeeded($tenant);
$redirectUrl = $request->get('redirect');
$useTokenAuth = $request->get('tokenAuth');
$loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');
if (! empty($useTokenAuth)) {
$itineraryUrl = route('login.token');
if (! empty($redirectUrl)) {
$itineraryUrl .= '?returnTo=' . $redirectUrl;
}
$itineraryUrl = urlencode($itineraryUrl);
$loginUrl .= '?returnTo=' . $itineraryUrl;
}
return response()->json([
'login_url' => $loginUrl,
]);
}
private function responseErrorNotFound(): JsonResponse
{
return response()->json([
'errors' => [
'not-found',
],
'message' => "Sorry, we can't find your account. Please contact Support if you need further assistance",
], SymfonyResponse::HTTP_NOT_FOUND);
}
}
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:...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JY-20891-improve-sms-text-relays, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.08843085,"height":0.025538707},"on_screen":true,"help_text":"Git Branch: JY-20891-improve-sms-text-relays","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.8081782,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"bounds":{"left":0.8234708,"top":0.019952115,"width":0.09208777,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.38397607,"top":0.15003991,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.39361703,"top":0.14844373,"width":0.00731383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.40093085,"top":0.14844373,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Http\\Controllers\\API;\n\nuse Illuminate\\Http\\JsonResponse;\nuse Illuminate\\Http\\Request;\nuse Jiminny\\Component\\Saml2\\FederationMetadata;\nuse Jiminny\\Http\\Responses\\Api\\Response;\nuse Jiminny\\Models\\User;\nuse Slides\\Saml2\\Models\\Tenant;\nuse Symfony\\Component\\HttpFoundation\\Response as SymfonyResponse;\n\nclass SsoController extends BaseController\n{\n /**\n * Create a new controller instance.\n */\n public function __construct(Response $response)\n {\n parent::__construct($response);\n\n $this->response = $response;\n }\n\n /**\n * Return the SSO login URL given user email\n */\n public function ssoLogin(Request $request): JsonResponse\n {\n $user = User::where('email', $request->email)->first();\n\n if (! $user instanceof User) {\n return $this->responseErrorNotFound();\n }\n\n $tenant = $user->getTeam()->getTenant();\n if (! $tenant instanceof Tenant) {\n return $this->responseErrorNotFound();\n }\n\n // Schedule async refresh of Azure federation metadata XML (if needed)\n $metadata = app()->make(FederationMetadata::class);\n $metadata->refreshMetadataAsyncIfNeeded($tenant);\n\n $redirectUrl = $request->get('redirect');\n $useTokenAuth = $request->get('tokenAuth');\n\n $loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');\n\n if (! empty($useTokenAuth)) {\n $itineraryUrl = route('login.token');\n if (! empty($redirectUrl)) {\n $itineraryUrl .= '?returnTo=' . $redirectUrl;\n }\n $itineraryUrl = urlencode($itineraryUrl);\n\n $loginUrl .= '?returnTo=' . $itineraryUrl;\n }\n\n return response()->json([\n 'login_url' => $loginUrl,\n ]);\n }\n\n private function responseErrorNotFound(): JsonResponse\n {\n return response()->json([\n 'errors' => [\n 'not-found',\n ],\n 'message' => \"Sorry, we can't find your account. Please contact Support if you need further assistance\",\n ], SymfonyResponse::HTTP_NOT_FOUND);\n }\n}","depth":4,"bounds":{"left":0.11968085,"top":0.14684756,"width":0.28823137,"height":0.8324022},"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Http\\Controllers\\API;\n\nuse Illuminate\\Http\\JsonResponse;\nuse Illuminate\\Http\\Request;\nuse Jiminny\\Component\\Saml2\\FederationMetadata;\nuse Jiminny\\Http\\Responses\\Api\\Response;\nuse Jiminny\\Models\\User;\nuse Slides\\Saml2\\Models\\Tenant;\nuse Symfony\\Component\\HttpFoundation\\Response as SymfonyResponse;\n\nclass SsoController extends BaseController\n{\n /**\n * Create a new controller instance.\n */\n public function __construct(Response $response)\n {\n parent::__construct($response);\n\n $this->response = $response;\n }\n\n /**\n * Return the SSO login URL given user email\n */\n public function ssoLogin(Request $request): JsonResponse\n {\n $user = User::where('email', $request->email)->first();\n\n if (! $user instanceof User) {\n return $this->responseErrorNotFound();\n }\n\n $tenant = $user->getTeam()->getTenant();\n if (! $tenant instanceof Tenant) {\n return $this->responseErrorNotFound();\n }\n\n // Schedule async refresh of Azure federation metadata XML (if needed)\n $metadata = app()->make(FederationMetadata::class);\n $metadata->refreshMetadataAsyncIfNeeded($tenant);\n\n $redirectUrl = $request->get('redirect');\n $useTokenAuth = $request->get('tokenAuth');\n\n $loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');\n\n if (! empty($useTokenAuth)) {\n $itineraryUrl = route('login.token');\n if (! empty($redirectUrl)) {\n $itineraryUrl .= '?returnTo=' . $redirectUrl;\n }\n $itineraryUrl = urlencode($itineraryUrl);\n\n $loginUrl .= '?returnTo=' . $itineraryUrl;\n }\n\n return response()->json([\n 'login_url' => $loginUrl,\n ]);\n }\n\n private function responseErrorNotFound(): JsonResponse\n {\n return response()->json([\n 'errors' => [\n 'not-found',\n ],\n 'message' => \"Sorry, we can't find your account. Please contact Support if you need further assistance\",\n ], SymfonyResponse::HTTP_NOT_FOUND);\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.40957448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.41821808,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"bounds":{"left":0.42918882,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43783244,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44647607,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.4574468,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46841756,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4950133,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.50598407,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.7084442,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"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}]...
|
-5018284905871611162
|
-8421505247229040959
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
3
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Http\Controllers\API;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jiminny\Component\Saml2\FederationMetadata;
use Jiminny\Http\Responses\Api\Response;
use Jiminny\Models\User;
use Slides\Saml2\Models\Tenant;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
class SsoController extends BaseController
{
/**
* Create a new controller instance.
*/
public function __construct(Response $response)
{
parent::__construct($response);
$this->response = $response;
}
/**
* Return the SSO login URL given user email
*/
public function ssoLogin(Request $request): JsonResponse
{
$user = User::where('email', $request->email)->first();
if (! $user instanceof User) {
return $this->responseErrorNotFound();
}
$tenant = $user->getTeam()->getTenant();
if (! $tenant instanceof Tenant) {
return $this->responseErrorNotFound();
}
// Schedule async refresh of Azure federation metadata XML (if needed)
$metadata = app()->make(FederationMetadata::class);
$metadata->refreshMetadataAsyncIfNeeded($tenant);
$redirectUrl = $request->get('redirect');
$useTokenAuth = $request->get('tokenAuth');
$loginUrl = url(config('saml2.routesPrefix') . '/' . $tenant->uuid . '/login');
if (! empty($useTokenAuth)) {
$itineraryUrl = route('login.token');
if (! empty($redirectUrl)) {
$itineraryUrl .= '?returnTo=' . $redirectUrl;
}
$itineraryUrl = urlencode($itineraryUrl);
$loginUrl .= '?returnTo=' . $itineraryUrl;
}
return response()->json([
'login_url' => $loginUrl,
]);
}
private function responseErrorNotFound(): JsonResponse
{
return response()->json([
'errors' => [
'not-found',
],
'message' => "Sorry, we can't find your account. Please contact Support if you need further assistance",
], SymfonyResponse::HTTP_NOT_FOUND);
}
}
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:...
|
34723
|
NULL
|
NULL
|
NULL
|
|
34725
|
1299
|
11
|
2026-05-13T11:35:07.246968+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-13/1778 /Users/lukas/.screenpipe/data/data/2026-05-13/1778672107246_m1.jpg...
|
PhpStorm
|
faVsco.js – SsoController.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"JY-20891-improve-sms-text-relays, menu","depth":5,"on_screen":true,"help_text":"Git Branch: JY-20891-improve-sms-text-relays","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AskJiminnyReportActivityServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AskJiminnyReportActivityServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3217526785416111167
|
-8132290182084711486
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
JY-20891-improve-sms-text Project: faVsco.js, menu
JY-20891-improve-sms-text-relays, menu
Start Listening for PHP Debug Connections
AskJiminnyReportActivityServiceTest
Run 'AskJiminnyReportActivityServiceTest'
Debug 'AskJiminnyReportActivityServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
iTerm2ShellEditViewSessionScripts|ProfilesWindowHelpAPP (-zsh)APP (-zsh)> 083(allSupport Daily - in 25 mADOCKERDEV (docker)882-zshdelete mode 100644 app/Component/ES/Worker/WorkerAmount.phpdelete mode 100644 app/Component/ES/Worker/WorkerInterface.phpcreate mode 100644 app/Component/ProphetAi/Exceptions/InsufficientTranscriptException.phpcreate mode 100644 app/Component/Transcription/DTO/Http/Transcription/AssemblyAI/AssemblyAI/NoAssemblyIdException.phpcreate mode 100644 app/Component/Transcription/DTO/Http/Transcription/TranscriptionIsNotCorrectFormatException.phpcreate mode100644app/Console/Commands/Crm/Backfill0pportunityUserFromAccountCommand.phpdelete mode100644 app/Console/Commands/Elasticsearch/AsyncUpdateEsActivities.phpcreate mode 100644 front-end/src/components/shared/modals/EntityPickerModal/__tests__/useEntitiesCache.spec.tscreate mode 100644 tests/Feature/Component/Nudge/ProcessOrganisationImmediateNudgesJobTest.phpcreate mode 100644 tests/Unit/Component/AiAutomation/Services/CrmFillingEligibilityCheckerTest.phpdelete mode 100644 tests/Unit/Component/ES/ElasticSearchWorkerManagerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/ActivityWorkerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/EntityWorkerTest.phpdelete mode 100644 tests/Unit/Component/ES/Worker/WorkerAmountTest.phpcreate mode 100644 tests/Unit/Component/ParticipantSpeech/Services/ParticipantSpeechesCreatorTest.phpcreatemode 100644 tests/Unit/Http/Controllers/Kiosk/ActivityControllerTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (master) $ git pullremote:Enumerating objects: 29,done.remote: Counting objects: 100% (29/29), done.remote: Compressing objects: 100% (20/20), done.remote: Total 29 (delta 14), reused 11 (delta 9), pack-reused 0 (from 0)Unpacking objects: 100% (29/29), 16.36 KiB | 644.00 KiB/s, done.From github.com:jiminny/appObfd964b74..3893b9772cmaster-> origin/master4f960247ed..4fe0405141JY-20820-es-reindex-stream-model-hydration -> origin/JY-20820-es-reindex-stream-model-hydration1ff6f70f48..62a7fe6277remove-phpstan-errors-> origin/remove-phpstan-errorsUpdating 0bfd964b74..3893b9772cFast-forwardapp/Component/Encoding/Job/AnalyzeTrackChannelsJob.phpapp/Component/FFMpeg/Services/GetSpeechIntervalsService.phpapp/Console/Commands/Activities/SetupIntegration/TwilioSetS3RecordingCredentialsCommand.php201894app/Console/Kernel.phpapp/Jobs/ImportRemoteTrackJob.phpapp/Services/Activity/Twilio/S3RecordingCredentialsService.phptests/Feature/Jobs/ImportRemoteTrackJobTest.phptests/Unit/Component/Encoding/Job/AnalyzeTrackChannelsJobTest.phptests/Unit/Component/FFMpeg/Services/GetSpeechIntervalsTest.phptests/Unit/Services/Activity/Twilio/S3RecordingCredentialsServiceTest.php7882285523618010 files changed, 823 insertions(+), 23 deletions(-)create mode 100644 app/Console/Commands/Activities/SetupIntegration/TwilioSetS3RecordingCredentialsCommand.phpcreate mode 100644 app/Services/Activity/Twilio/S3RecordingCredentialsService.phpcreate mode 100644 tests/Unit/Services/Activity/Twilio/S3RecordingCredentialsServiceTest.phplukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (master) $ co -b JY-20891-improve-sms-text-relaysSwitched to a new branch 'JY-20891-improve-sms-text-relays'lukas@Lukas-Kovaliks-MacBook-Pro-Jiminny ~/jiminny/app (JY-20891-improve-sms-text-relays) $ |||84100% <78• Wed 13 May 14:35:07screenpipe"18185APP...
|
34722
|
NULL
|
NULL
|
NULL
|