Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 72
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
TrackingExtensionDeployEventListener
0.00% covered (danger)
0.00%
0 / 72
0.00% covered (danger)
0.00%
0 / 4
650
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 handle
0.00% covered (danger)
0.00%
0 / 49
0.00% covered (danger)
0.00%
0 / 1
182
 getSiteNameFromUrl
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 updateSync
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2
3namespace App\Listeners;
4
5use App\Events\TrackingExtensionDeployEvent;
6use App\Http\Models\Auth\User;
7use App\Http\Models\FlymsgDeploymentRecord;
8use App\Http\Models\HubspotProperties;
9use App\Http\Models\Shortcut;
10use App\Http\Models\UserInfo;
11use App\Http\Services\StatisticsService;
12use App\Services\UserInfo\UserInfoService;
13use Carbon\Carbon;
14use Exception;
15use Symfony\Component\HttpFoundation\Response;
16
17class TrackingExtensionDeployEventListener
18{
19    public function __construct(
20        private StatisticsService $statisticsService
21    ) {}
22
23    public function handle(TrackingExtensionDeployEvent $event)
24    {
25        // Access the parameters within the job's handle method
26        $user = $event->user;
27        $data = $event->data;
28
29        $shortcut = $event->shortcut;
30        $browser_type = $event->browserType;
31
32        if ($shortcut) {
33            $shortcut = Shortcut::find($shortcut->id);
34        }
35
36        try {
37            if ($data['shortcut_id'] != 0000) {
38                $charactersTyped = strlen(strip_tags($shortcut->text));
39                $shortcutCharacters = strlen(strip_tags($shortcut->shortcut));
40            } else {
41                $charactersTyped = $data['value'];
42                $shortcutCharacters = 4;
43            }
44
45            // $record = HubspotProperties::where('flymsg_id', $data['user_id'])->get();
46
47            $charactersSaved = $charactersTyped > $shortcutCharacters ? $charactersTyped - $shortcutCharacters : $charactersTyped;
48            $timeSaved = $this->statisticsService->getTimeSaved($user, $charactersSaved);
49            $costSaved = $this->statisticsService->getCostSaved($user, $timeSaved, now());
50
51            // Update Usage data on the shortcut model for quick access.
52            if ($data['shortcut_id'] != 0000) {
53
54                // This is being done already in the TrackingExtensionController line 117.
55                // Don't uncomment this to avoid duplicate entries.
56                // Left here for demo only
57                if (isset($shortcut->flycutUsage_count)) {
58                    // $shortcut->flycutUsage_count = $shortcut->flycutUsage_count + 1;
59                } else {
60                    $shortcut->flycutUsage_count = 1;
61                }
62
63                if (isset($shortcut->flycutUsage_time_saved)) {
64                    $shortcut->flycutUsage_time_saved = $shortcut->flycutUsage_time_saved + $timeSaved;
65                } else {
66                    $shortcut->flycutUsage_time_saved = $timeSaved;
67                }
68
69                if (isset($shortcut->flycutUsage_cost_saved)) {
70                    $shortcut->flycutUsage_cost_saved = $shortcut->flycutUsage_cost_saved + $costSaved;
71                } else {
72                    $shortcut->flycutUsage_cost_saved = $costSaved;
73                }
74
75                // Update last_deployed_date for recently used.
76                $shortcut->last_deployed_date = Carbon::now()->toIso8601String();
77                $shortcut->save();
78            }
79
80            $user->flycutUsage()->create([
81                'shortcut_id' => $data['shortcut_id'] == 0000 ? 1 : $data['shortcut_id'],
82                'characters_typed' => $charactersTyped,
83                'shortcut_characters' => $shortcutCharacters,
84                'characters_saved' => $charactersSaved,
85                'time_saved' => $timeSaved,
86                'cost_saved' => $costSaved,
87                'executed_at_raw' => $data['executed_at'],
88                'executed_at' => $this->getSiteNameFromUrl($data['executed_at']),
89            ]);
90
91            if ($data['tag'] === 'total_char_by_a_FlyCut' && $browser_type) {
92                $this->updateSync($user->id, $browser_type, $data);
93            }
94
95            $siteName = $this->getSiteNameFromUrl($data['executed_at']);
96            $monthYear = now()->format('M Y');
97
98            // Update or create a FlymsgDeployment record with the given site and date.
99            $record = FlymsgDeploymentRecord::where('site_name', $siteName)->where('month_year', $monthYear)->first();
100
101            if ($record) {
102                // We're going back to the db to avoid concurrency issues
103                FlymsgDeploymentRecord::firstWhere('_id', $record->id)->increment('usage_count');
104            } else {
105                FlymsgDeploymentRecord::create([
106                    'site_name' => $siteName,
107                    'month_year' => $monthYear,
108                    'usage_count' => 1,
109                ]);
110            }
111        } catch (Exception $e) {
112            return response()->json(['data' => [], 'message' => $e->getMessage(), 'error' => 1], Response::HTTP_INTERNAL_SERVER_ERROR);
113        }
114    }
115
116    /**
117     * Gets the name of the site from a given URL.
118     *
119     * @param  string  $url  The URL to extract the site name from.
120     * @return string The name of the site without the "www." prefix, or an empty string if the URL is empty.
121     */
122    private function getSiteNameFromUrl(string $url)
123    {
124        if (empty($url)) {
125            return '';
126        }
127
128        $domain = parse_url($url, PHP_URL_HOST);
129
130        return preg_replace('/^www\./', '', $domain);
131    }
132
133    protected function updateSync($userId, $browser_type, $data)
134    {
135        // Start of Updating propreties.
136        $user = User::firstWhere('_id', $userId);
137        $userInfo = UserInfo::where('email', $user->email)->first();
138        if ($userInfo) {
139            $userInfo->email_used_for_login = $user->email;
140        }
141
142        $browser = strtolower($browser_type);
143
144        if ($userInfo) {
145            if ($userInfo->{"flymsg_{$browser}_extension_installed"} !== 'Yes' || $userInfo->{"flymsg_{$browser}_extension_uninstalled"} === 'Yes') {
146                $userInfoService = new UserInfoService(new StatisticsService);
147
148                $properties = $userInfoService->addExtension($userInfo, $browser, now());
149
150                $userInfo->fill($properties);
151            } else {
152                $userInfo->signed_into_flymsg_extension = 'Yes';
153                $userInfo->last_browser_used = ucfirst(strtolower($browser_type));
154            }
155
156            if ($data && $data['extension_tracking_headers']) {
157                if ($data['extension_tracking_headers']['flymsg_extension_version_for_chrome']) {
158                    $userInfo->flymsg_extension_version_for_chrome = $data['extension_tracking_headers']['flymsg_extension_version_for_chrome'];
159                }
160
161                if ($data['extension_tracking_headers']['flymsg_extension_version_for_edge']) {
162                    $userInfo->flymsg_extension_version_for_edge = $data['extension_tracking_headers']['flymsg_extension_version_for_edge'];
163                }
164            }
165
166            $userInfo->save();
167        }
168    }
169}