Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 310
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
UsersReportUsageExport
0.00% covered (danger)
0.00%
0 / 310
0.00% covered (danger)
0.00%
0 / 4
182
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 array
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
56
 headings
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
6
 getUserUsageData
0.00% covered (danger)
0.00%
0 / 227
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3namespace App\Exports;
4
5use App\Http\Models\Auth\User;
6use App\Traits\AccountCenter\Reporting\ChartTrait;
7use Carbon\Carbon;
8use Carbon\CarbonPeriod;
9use MongoDB\BSON\UTCDateTime;
10use Vitorccs\LaravelCsv\Concerns\Exportable;
11use Vitorccs\LaravelCsv\Concerns\FromArray;
12use Vitorccs\LaravelCsv\Concerns\WithHeadings;
13
14class UsersReportUsageExport implements FromArray, WithHeadings
15{
16    use ChartTrait;
17    use Exportable;
18
19    public $company_id;
20
21    public $from_date;
22
23    public $to_date;
24
25    public $user_ids;
26
27    public $group_ids;
28
29    public $subgroup_ids;
30
31    public function __construct($company_id, $from_date, $to_date, $user_ids, $group_ids, $subgroup_ids)
32    {
33        $this->company_id = $company_id;
34        $this->from_date = $from_date;
35        $this->to_date = $to_date;
36        $this->user_ids = $user_ids;
37        $this->group_ids = $group_ids;
38        $this->subgroup_ids = $subgroup_ids;
39    }
40
41    public function array(): array
42    {
43        $users = User::select([
44            'id',
45            'first_name',
46            'last_name',
47            'company_group_id',
48            'company_id',
49            'deleted_at',
50            'avatar',
51        ])
52            ->where('company_id', $this->company_id)
53            ->get();
54
55        $ids = $users->pluck('id')->toArray();
56
57        $start_date = $this->from_date;
58        $end_date = $this->to_date;
59
60        if ($start_date && $end_date) {
61            $start_date = Carbon::parse($start_date)->startOfDay();
62            $end_date = Carbon::parse($end_date)->endOfDay();
63            $start_date = $start_date->setTimezone('UTC')->startOfDay();
64            $end_date = $end_date->setTimezone('UTC')->endOfDay();
65            $start_date = new UTCDateTime($start_date->getTimestamp() * 1000);
66            $end_date = new UTCDateTime($end_date->getTimestamp() * 1000);
67        }
68
69        $usageData = $this->getUserUsageData($ids, $start_date, $end_date);
70
71        $period = CarbonPeriod::create($this->from_date, $this->to_date);
72        $data = [];
73
74        foreach ($usageData as $item) {
75            $monthCollection = collect($item->monthly_usage);
76            $identifier = $item->subscription_data?->plan?->identifier ?? 'freemium';
77            $row = [
78                'first_name' => $item->first_name ?? '',
79                'last_name' => $item->last_name ?? '',
80                'email' => $item->email ?? '',
81                'license_type' => $this->parseSubscriptionPlanName($identifier),
82                'flymsg_account_creation_date' => $item->account_creation_date ?? '',
83                'extension_installed_on_any_browser' => ($item->flymsg_chrome_extension_installed == 'Yes' || $item->flymsg_edge_extension_installed == 'Yes') ? 'Yes' : 'No',
84                'last_login_to_flymsg' => $item->last_login ?? '',
85                'sentence_rewrite_ai_used' => round(collect($item->monthly_usage)->sum('sentence_rewrite_count') ?? 0, 2),
86                'paragraph_rewrite_ai_used' => round(collect($item->monthly_usage)->sum('paragraph_rewrite_count') ?? 0, 2),
87                'flyengage_ai_used' => round(collect($item->monthly_usage)->sum('flyengage_count') ?? 0, 2),
88                'flyposts_ai_used' => round(collect($item->monthly_usage)->sum('flypost_count') ?? 0, 2),
89                'no_of_flycuts_created' => $item->shortcuts_created ?? 0,
90                'no_of_flyplates_added_to_flycuts' => $item->flyplates_created ?? 0,
91                'characters_typed_by_flymsg' => round($monthCollection->sum('characters_typed_by_flymsg') ?? 0, 2),
92                'time_saved_by_flymsg' => round($monthCollection->sum('time_saved_by_flymsg') ?? 0, 2),
93                'cost_saved_by_flymsg' => round($monthCollection->sum('cost_saved_by_flymsg') ?? 0, 2),
94            ];
95            foreach ($period as $date) {
96                $year_month = $date->format('Y-m');
97                $month_year = $date->format('M Y');
98                $month = $monthCollection->firstWhere('month_year', $year_month);
99                $row["characters_typed_by_flymsg___$month_year"] = round($month?->characters_typed_by_flymsg ?? 0, 2);
100                $row["time_saved_by_flymsg___$month_year"] = round($month?->time_saved_by_flymsg ?? 0, 2);
101                $row["cost_saved_by_flymsg___$month_year"] = round($month?->cost_saved_by_flymsg ?? 0, 2);
102            }
103            $data[] = $row;
104        }
105
106        return $data;
107    }
108
109    public function headings(): array
110    {
111        $headers = [
112            'Firstname',
113            'Lastname',
114            'Email',
115            'License Type',
116            'FlyMSG Account Creation Date',
117            'Extension Installed on Any Browser',
118            'Last Login to FlyMSG',
119            'Total # of Times FlyEngage AI Used (Count)',
120            'Total # of Times FlyPosts AI Used (Count)',
121            '# of FlyCuts Created (Count)',
122            '# of FlyPlates Added to FlyCuts (Count)',
123            'Total # of Characters Typed by FlyMSG by User',
124            'Total Time Saved by FlyMSG by User',
125            'Total Cost Savings by FlyMSG by User',
126        ];
127
128        $period = CarbonPeriod::create($this->from_date, '1 month', $this->to_date); // Ensure monthly periods
129
130        foreach ($period as $date) {
131            $month_year = $date->format('M Y');
132            $headers[] = "Total # of Characters Typed by FlyMSG by User $month_year";
133            $headers[] = "Total Time Saved by FlyMSG by User $month_year";
134            $headers[] = "Total Cost Savings by FlyMSG by User $month_year";
135        }
136
137        return $headers;
138    }
139
140    private function getUserUsageData($userIds, $startDate, $endDate)
141    {
142        $results = User::withoutGlobalScopes()->raw(function ($collection) use ($userIds, $startDate, $endDate) {
143            $matchExpression = [
144                ['$eq' => ['$flymsg_id', '$$userId']],
145            ];
146
147            if ($startDate) {
148                $matchExpression[] = ['$gte' => ['$created_at', $startDate]];
149            }
150
151            if ($endDate) {
152                $matchExpression[] = ['$lte' => ['$created_at', $endDate]];
153            }
154
155            return $collection->aggregate([
156                [
157                    '$match' => [
158                        '_id' => ['$in' => array_map(function ($userId) {
159                            return new \MongoDB\BSON\ObjectId($userId);
160                        }, $userIds)],
161                    ],
162                ],
163                [
164                    '$lookup' => [
165                        'from' => 'hubspot_properties',
166                        'let' => ['userId' => ['$toString' => '$_id']],
167                        'pipeline' => [
168                            [
169                                '$match' => [
170                                    '$expr' => [
171                                        '$and' => $matchExpression,
172                                    ],
173                                ],
174                            ],
175                            ['$sort' => ['last_login' => -1]],
176                            ['$limit' => 1],
177                            [
178                                '$project' => [
179                                    'subscription_type' => 1,
180                                    'account_creation_date' => 1,
181                                    'last_login' => 1,
182                                    'flymsg_chrome_extension_installed' => 1,
183                                    'flymsg_edge_extension_installed' => 1,
184                                ],
185                            ],
186                        ],
187                        'as' => 'hubspot_data',
188                    ],
189                ],
190                [
191                    '$lookup' => [
192                        'from' => 'flycut_usage',
193                        'let' => ['userId' => ['$toString' => '$_id']],
194                        'pipeline' => [
195                            [
196                                '$match' => [
197                                    '$expr' => [
198                                        '$and' => [
199                                            ['$eq' => ['$user_id', '$$userId']],
200                                            ['$gte' => ['$created_at', $startDate]],
201                                            ['$lte' => ['$created_at', $endDate]],
202                                        ],
203                                    ],
204                                ],
205                            ],
206                            [
207                                '$group' => [
208                                    '_id' => [
209                                        'month_year' => [
210                                            '$dateToString' => [
211                                                'format' => '%Y-%m',
212                                                'date' => '$created_at',
213                                            ],
214                                        ],
215                                    ],
216                                    'characters_typed' => ['$sum' => '$characters_typed'],
217                                    'time_saved' => ['$sum' => '$time_saved'],
218                                    'cost_saved' => ['$sum' => '$cost_saved'],
219                                    'flypost_count' => [
220                                        '$sum' => [
221                                            '$cond' => [['$eq' => ['$feature', 'flypost']], 1, 0],
222                                        ],
223                                    ],
224                                    'flyengage_count' => [
225                                        '$sum' => [
226                                            '$cond' => [['$eq' => ['$feature', 'flyengage']], 1, 0],
227                                        ],
228                                    ],
229                                    'sentence_rewrite_count' => [
230                                        '$sum' => [
231                                            '$cond' => [['$eq' => ['$feature', 'sentence_rewrite']], 1, 0],
232                                        ],
233                                    ],
234                                    'paragraph_rewrite_count' => [
235                                        '$sum' => [
236                                            '$cond' => [['$eq' => ['$feature', 'paragraph_rewrite']], 1, 0],
237                                        ],
238                                    ],
239                                ],
240                            ],
241                            ['$sort' => ['_id.month_year' => 1]],
242                        ],
243                        'as' => 'monthly_usage_data',
244                    ],
245                ],
246                [
247                    '$lookup' => [
248                        'from' => 'shortcuts',
249                        'let' => ['userId' => ['$toString' => '$_id']],
250                        'pipeline' => [
251                            [
252                                '$match' => [
253                                    '$expr' => [
254                                        '$and' => [
255                                            ['$eq' => ['$user_id', '$$userId']],
256                                            ['$gte' => ['$created_at', $startDate]],
257                                            ['$lte' => ['$created_at', $endDate]],
258                                        ],
259                                    ],
260                                ],
261                            ],
262                            [
263                                '$group' => [
264                                    '_id' => null,
265                                    'shortcuts_created' => [
266                                        '$sum' => ['$cond' => [['$eq' => ['$user_defined', true]], 1, 0]],
267                                    ],
268                                    'flyplates_created' => [
269                                        '$sum' => ['$cond' => [['$eq' => ['$user_defined', false]], 1, 0]],
270                                    ],
271                                ],
272                            ],
273                        ],
274                        'as' => 'shortcuts_data',
275                    ],
276                ],
277                [
278                    '$lookup' => [
279                        'from' => 'subscriptions',
280                        'let' => ['userId' => ['$toString' => '$_id']],
281                        'pipeline' => [
282                            [
283                                '$match' => [
284                                    '$expr' => [
285                                        '$and' => [
286                                            ['$eq' => ['$user_id', '$$userId']],
287                                            ['$gte' => ['$name', 'main']],
288                                            ['$lte' => ['$stripe_status', 'active']],
289                                        ],
290                                    ],
291                                ],
292                            ],
293                            [
294                                '$sort' => [
295                                    'created_at' => -1,
296                                ],
297                            ],
298                            [
299                                '$limit' => 1,
300                            ],
301                            [
302                                '$lookup' => [
303                                    'from' => 'plans',
304                                    'localField' => 'stripe_plan',
305                                    'foreignField' => 'stripe_id',
306                                    'as' => 'plan',
307                                ],
308                            ],
309                            [
310                                '$project' => [
311                                    'plan' => [
312                                        '$arrayElemAt' => ['$plan', 0],
313                                    ],
314                                    'subscription' => '$$ROOT',
315                                ],
316                            ],
317                        ],
318                        'as' => 'subscription_data',
319                    ],
320                ],
321                [
322                    '$unwind' => [
323                        'path' => '$hubspot_data',
324                        'preserveNullAndEmptyArrays' => true,
325                    ],
326                ],
327                [
328                    '$unwind' => [
329                        'path' => '$shortcuts_data',
330                        'preserveNullAndEmptyArrays' => true,
331                    ],
332                ],
333                [
334                    '$unwind' => [
335                        'path' => '$subscription_data',
336                        'preserveNullAndEmptyArrays' => true,
337                    ],
338                ],
339                [
340                    '$project' => [
341                        'user_id' => ['$toString' => '$_id'],
342                        'first_name' => 1,
343                        'last_name' => 1,
344                        'email' => 1,
345
346                        'subscription_data' => 1,
347
348                        // Dados do Hubspot
349                        'subscription_type' => '$hubspot_data.subscription_type',
350                        'account_creation_date' => '$hubspot_data.account_creation_date',
351                        'last_login' => '$hubspot_data.last_login',
352                        'flymsg_chrome_extension_installed' => '$hubspot_data.flymsg_chrome_extension_installed',
353                        'flymsg_edge_extension_installed' => '$hubspot_data.flymsg_edge_extension_installed',
354
355                        // Dados de Flycut Usage Mensal
356                        'monthly_usage' => [
357                            '$map' => [
358                                'input' => '$monthly_usage_data',
359                                'as' => 'usage',
360                                'in' => [
361                                    'month_year' => '$$usage._id.month_year',
362                                    'characters_typed_by_flymsg' => '$$usage.characters_typed',
363                                    'time_saved_by_flymsg' => '$$usage.time_saved',
364                                    'cost_saved_by_flymsg' => '$$usage.cost_saved',
365                                    'flypost_count' => '$$usage.flypost_count',
366                                    'flyengage_count' => '$$usage.flyengage_count',
367                                    'sentence_rewrite_count' => '$$usage.sentence_rewrite_count',
368                                    'paragraph_rewrite_count' => '$$usage.paragraph_rewrite_count',
369                                ],
370                            ],
371                        ],
372
373                        // Dados de Shortcuts
374                        'shortcuts_created' => '$shortcuts_data.shortcuts_created',
375                        'flyplates_created' => '$shortcuts_data.flyplates_created',
376                    ],
377                ],
378            ]);
379        });
380
381        return $results;
382    }
383}