Issues (3627)

LeadBundle/Controller/CompanyController.php (2 issues)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\LeadBundle\Controller;
13
14
use Mautic\CoreBundle\Controller\FormController;
15
use Mautic\CoreBundle\Factory\PageHelperFactoryInterface;
16
use Mautic\CoreBundle\Helper\InputHelper;
17
use Mautic\LeadBundle\Entity\Company;
18
use Mautic\LeadBundle\Form\Type\CompanyMergeType;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\Response;
21
22
class CompanyController extends FormController
23
{
24
    use LeadDetailsTrait;
25
26
    /**
27
     * @param int $page
28
     *
29
     * @return JsonResponse|Response
30
     */
31
    public function indexAction($page = 1)
32
    {
33
        //set some permissions
34
        $permissions = $this->get('mautic.security')->isGranted(
35
            [
36
                'lead:leads:viewown',
37
                'lead:leads:viewother',
38
                'lead:leads:create',
39
                'lead:leads:editother',
40
                'lead:leads:editown',
41
                'lead:leads:deleteown',
42
                'lead:leads:deleteother',
43
            ],
44
            'RETURN_ARRAY'
45
        );
46
47
        if (!$permissions['lead:leads:viewother'] && !$permissions['lead:leads:viewown']) {
48
            return $this->accessDenied();
49
        }
50
51
        $this->setListFilters();
52
53
        /** @var PageHelperFactoryInterface $pageHelperFacotry */
54
        $pageHelperFacotry = $this->get('mautic.page.helper.factory');
55
        $pageHelper        = $pageHelperFacotry->make('mautic.company', $page);
56
57
        $limit      = $pageHelper->getLimit();
58
        $start      = $pageHelper->getStart();
59
        $search     = $this->request->get('search', $this->get('session')->get('mautic.company.filter', ''));
60
        $filter     = ['string' => $search, 'force' => []];
61
        $orderBy    = $this->get('session')->get('mautic.company.orderby', 'comp.companyname');
62
        $orderByDir = $this->get('session')->get('mautic.company.orderbydir', 'ASC');
63
64
        $companies = $this->getModel('lead.company')->getEntities(
65
            [
66
                'start'          => $start,
67
                'limit'          => $limit,
68
                'filter'         => $filter,
69
                'orderBy'        => $orderBy,
70
                'orderByDir'     => $orderByDir,
71
                'withTotalCount' => true,
72
            ]
73
        );
74
75
        $this->get('session')->set('mautic.company.filter', $search);
76
77
        $count     = $companies['count'];
78
        $companies = $companies['results'];
79
80
        if ($count && $count < ($start + 1)) {
81
            $lastPage  = $pageHelper->countPage($count);
82
            $returnUrl = $this->generateUrl('mautic_company_index', ['page' => $lastPage]);
83
            $pageHelper->rememberPage($lastPage);
84
85
            return $this->postActionRedirect(
86
                [
87
                    'returnUrl'       => $returnUrl,
88
                    'viewParameters'  => ['page' => $lastPage],
89
                    'contentTemplate' => 'MauticLeadBundle:Company:index',
90
                    'passthroughVars' => [
91
                        'activeLink'    => '#mautic_company_index',
92
                        'mauticContent' => 'company',
93
                    ],
94
                ]
95
            );
96
        }
97
98
        $pageHelper->rememberPage($page);
99
100
        $tmpl       = $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index';
101
        $model      = $this->getModel('lead.company');
102
        $companyIds = array_keys($companies);
103
        $leadCounts = (!empty($companyIds)) ? $model->getRepository()->getLeadCount($companyIds) : [];
104
105
        return $this->delegateView(
106
            [
107
                'viewParameters' => [
108
                    'searchValue' => $search,
109
                    'leadCounts'  => $leadCounts,
110
                    'items'       => $companies,
111
                    'page'        => $page,
112
                    'limit'       => $limit,
113
                    'permissions' => $permissions,
114
                    'tmpl'        => $tmpl,
115
                    'totalItems'  => $count,
116
                ],
117
                'contentTemplate' => 'MauticLeadBundle:Company:list.html.php',
118
                'passthroughVars' => [
119
                    'activeLink'    => '#mautic_company_index',
120
                    'mauticContent' => 'company',
121
                    'route'         => $this->generateUrl('mautic_company_index', ['page' => $page]),
122
                ],
123
            ]
124
        );
125
    }
126
127
    /**
128
     * Refresh contacts list in company view with new parameters like order or page.
129
     *
130
     * @param int $objectId company id
131
     * @param int $page
132
     *
133
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
134
     */
135
    public function contactsListAction($objectId, $page = 1)
136
    {
137
        if (empty($objectId)) {
138
            return $this->accessDenied();
139
        }
140
141
        //set some permissions
142
        $permissions = $this->get('mautic.security')->isGranted(
143
            [
144
                'lead:leads:viewown',
145
                'lead:leads:viewother',
146
                'lead:leads:create',
147
                'lead:leads:editown',
148
                'lead:leads:editother',
149
                'lead:leads:deleteown',
150
                'lead:leads:deleteother',
151
            ],
152
            'RETURN_ARRAY'
153
        );
154
155
        /** @var \Mautic\LeadBundle\Model\CompanyModel $model */
156
        $model  = $this->getModel('lead.company');
157
158
        /** @var \Mautic\LeadBundle\Entity\Company $company */
159
        $company = $model->getEntity($objectId);
160
161
        $companiesRepo  = $model->getCompanyLeadRepository();
162
        $contacts       = $companiesRepo->getCompanyLeads($objectId);
163
164
        $leadsIds = 'ids:';
165
        foreach ($contacts as $contact) {
166
            $leadsIds .= $contact['lead_id'].',';
167
        }
168
        $leadsIds = substr($leadsIds, 0, -1);
169
170
        $data = $this->getCompanyContacts($objectId, $page, $leadsIds);
171
172
        return $this->delegateView(
173
            [
174
                'viewParameters' => [
175
                    'company'     => $company,
176
                    'page'        => $data['page'],
177
                    'contacts'    => $data['items'],
178
                    'totalItems'  => $data['count'],
179
                    'limit'       => $data['limit'],
180
                    'permissions' => $permissions,
181
                    'security'    => $this->get('mautic.security'),
182
                ],
183
                'contentTemplate' => 'MauticLeadBundle:Company:list_rows_contacts.html.php',
184
            ]
185
        );
186
    }
187
188
    /**
189
     * Generates new form and processes post data.
190
     *
191
     * @param \Mautic\LeadBundle\Entity\Company $entity
192
     *
193
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
194
     */
195
    public function newAction($entity = null)
196
    {
197
        $model = $this->getModel('lead.company');
198
199
        if (!($entity instanceof Company)) {
200
            /** @var \Mautic\LeadBundle\Entity\Company $entity */
201
            $entity = $model->getEntity();
202
        }
203
204
        if (!$this->get('mautic.security')->isGranted('lead:leads:create')) {
205
            return $this->accessDenied();
206
        }
207
208
        //set the page we came from
209
        $page         = $this->get('session')->get('mautic.company.page', 1);
210
        $method       = $this->request->getMethod();
211
        $action       = $this->generateUrl('mautic_company_action', ['objectAction' => 'new']);
212
        $company      = $this->request->request->get('company', []);
213
        $updateSelect = InputHelper::clean(
214
            'POST' === $method
215
                ? ($company['updateSelect'] ?? false)
216
                : $this->request->get('updateSelect', false)
217
        );
218
219
        $fields = $this->getModel('lead.field')->getPublishedFieldArrays('company');
220
        $form   = $model->createForm($entity, $this->get('form.factory'), $action, ['fields' => $fields, 'update_select' => $updateSelect]);
221
222
        $viewParameters = ['page' => $page];
223
        $returnUrl      = $this->generateUrl('mautic_company_index', $viewParameters);
224
        $template       = 'MauticLeadBundle:Company:index';
225
226
        ///Check for a submitted form and process it
227
        if ('POST' == $this->request->getMethod()) {
228
            $valid = false;
229
            if (!$cancelled = $this->isFormCancelled($form)) {
230
                if ($valid = $this->isFormValid($form)) {
231
                    //form is valid so process the data
232
                    //get custom field values
233
                    $data = $this->request->request->get('company');
234
                    //pull the data from the form in order to apply the form's formatting
235
                    foreach ($form as $f) {
236
                        $data[$f->getName()] = $f->getData();
237
                    }
238
                    $model->setFieldValues($entity, $data, true);
239
                    //form is valid so process the data
240
                    $model->saveEntity($entity);
241
242
                    $this->addFlash(
0 ignored issues
show
Deprecated Code introduced by
The function Mautic\CoreBundle\Contro...nController::addFlash() has been deprecated: Will be removed in Mautic 3.0. Use CommonController::flashBag->addFlash() instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

242
                    /** @scrutinizer ignore-deprecated */ $this->addFlash(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
243
                        'mautic.core.notice.created',
244
                        [
245
                            '%name%'      => $entity->getName(),
246
                            '%menu_link%' => 'mautic_company_index',
247
                            '%url%'       => $this->generateUrl(
248
                                'mautic_company_action',
249
                                [
250
                                    'objectAction' => 'edit',
251
                                    'objectId'     => $entity->getId(),
252
                                ]
253
                            ),
254
                        ]
255
                    );
256
257
                    if ($form->get('buttons')->get('save')->isClicked()) {
258
                        $returnUrl = $this->generateUrl('mautic_company_index', $viewParameters);
259
                        $template  = 'MauticLeadBundle:Company:index';
260
                    } else {
261
                        //return edit view so that all the session stuff is loaded
262
                        return $this->editAction($entity->getId(), true);
263
                    }
264
                }
265
            }
266
267
            $passthrough = [
268
                'activeLink'    => '#mautic_company_index',
269
                'mauticContent' => 'company',
270
            ];
271
272
            // Check to see if this is a popup
273
            if (!empty($form['updateSelect'])) {
274
                $template    = false;
275
                $passthrough = array_merge(
276
                    $passthrough,
277
                    [
278
                        'updateSelect' => $form['updateSelect']->getData(),
279
                        'id'           => $entity->getId(),
280
                        'name'         => $entity->getName(),
281
                    ]
282
                );
283
            }
284
285
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
286
                return $this->postActionRedirect(
287
                    [
288
                        'returnUrl'       => $returnUrl,
289
                        'viewParameters'  => $viewParameters,
290
                        'contentTemplate' => $template,
291
                        'passthroughVars' => $passthrough,
292
                    ]
293
                );
294
            }
295
        }
296
297
        $fields = $model->organizeFieldsByGroup($fields);
298
        $groups = array_keys($fields);
299
        sort($groups);
300
        $template = 'MauticLeadBundle:Company:form_'.($this->request->get('modal', false) ? 'embedded' : 'standalone').'.html.php';
301
302
        return $this->delegateView(
303
            [
304
                'viewParameters' => [
305
                    'tmpl'   => $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index',
306
                    'entity' => $entity,
307
                    'form'   => $form->createView(),
308
                    'fields' => $fields,
309
                    'groups' => $groups,
310
                ],
311
                'contentTemplate' => $template,
312
                'passthroughVars' => [
313
                    'activeLink'    => '#mautic_company_index',
314
                    'mauticContent' => 'company',
315
                    'updateSelect'  => ('POST' == $this->request->getMethod()) ? $updateSelect : null,
316
                    'route'         => $this->generateUrl(
317
                        'mautic_company_action',
318
                        [
319
                            'objectAction' => (!empty($valid) ? 'edit' : 'new'), //valid means a new form was applied
320
                            'objectId'     => $entity->getId(),
321
                        ]
322
                    ),
323
                ],
324
            ]
325
        );
326
    }
327
328
    /**
329
     * Generates edit form and processes post data.
330
     *
331
     * @param int  $objectId
332
     * @param bool $ignorePost
333
     *
334
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
335
     */
336
    public function editAction($objectId, $ignorePost = false)
337
    {
338
        $model  = $this->getModel('lead.company');
339
        $entity = $model->getEntity($objectId);
340
341
        //set the page we came from
342
        $page = $this->get('session')->get('mautic.company.page', 1);
343
344
        $viewParameters = ['page' => $page];
345
346
        //set the return URL
347
        $returnUrl = $this->generateUrl('mautic_company_index', ['page' => $page]);
348
349
        $postActionVars = [
350
            'returnUrl'       => $returnUrl,
351
            'viewParameters'  => $viewParameters,
352
            'contentTemplate' => 'MauticLeadBundle:Company:index',
353
            'passthroughVars' => [
354
                'activeLink'    => '#mautic_company_index',
355
                'mauticContent' => 'company',
356
            ],
357
        ];
358
359
        //form not found
360
        if (null === $entity) {
361
            return $this->postActionRedirect(
362
                array_merge(
363
                    $postActionVars,
364
                    [
365
                        'flashes' => [
366
                            [
367
                                'type'    => 'error',
368
                                'msg'     => 'mautic.company.error.notfound',
369
                                'msgVars' => ['%id%' => $objectId],
370
                            ],
371
                        ],
372
                    ]
373
                )
374
            );
375
        } elseif (!$this->get('mautic.security')->hasEntityAccess(
376
            'lead:leads:editown',
377
            'lead:leads:editother',
378
            $entity->getOwner())) {
379
            return $this->accessDenied();
380
        } elseif ($model->isLocked($entity)) {
381
            //deny access if the entity is locked
382
            return $this->isLocked($postActionVars, $entity, 'lead.company');
383
        }
384
385
        $action       = $this->generateUrl('mautic_company_action', ['objectAction' => 'edit', 'objectId' => $objectId]);
386
        $method       = $this->request->getMethod();
387
        $company      = $this->request->request->get('company', []);
388
        $updateSelect = 'POST' === $method
389
            ? ($company['updateSelect'] ?? false)
390
            : $this->request->get('updateSelect', false);
391
392
        $fields = $this->getModel('lead.field')->getPublishedFieldArrays('company');
393
        $form   = $model->createForm(
394
            $entity,
395
            $this->get('form.factory'),
396
            $action,
397
            ['fields' => $fields, 'update_select' => $updateSelect]
398
        );
399
400
        ///Check for a submitted form and process it
401
        if (!$ignorePost && 'POST' === $method) {
402
            $valid = false;
403
404
            if (!$cancelled = $this->isFormCancelled($form)) {
405
                if ($valid = $this->isFormValid($form)) {
406
                    $data = $this->request->request->get('company');
407
                    //pull the data from the form in order to apply the form's formatting
408
                    foreach ($form as $f) {
409
                        $data[$f->getName()] = $f->getData();
410
                    }
411
412
                    $model->setFieldValues($entity, $data, true);
413
414
                    //form is valid so process the data
415
                    $model->saveEntity($entity, $form->get('buttons')->get('save')->isClicked());
416
417
                    $this->addFlash(
0 ignored issues
show
Deprecated Code introduced by
The function Mautic\CoreBundle\Contro...nController::addFlash() has been deprecated: Will be removed in Mautic 3.0. Use CommonController::flashBag->addFlash() instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

417
                    /** @scrutinizer ignore-deprecated */ $this->addFlash(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
418
                        'mautic.core.notice.updated',
419
                        [
420
                            '%name%'      => $entity->getName(),
421
                            '%menu_link%' => 'mautic_company_index',
422
                            '%url%'       => $this->generateUrl(
423
                                'mautic_company_action',
424
                                [
425
                                    'objectAction' => 'edit',
426
                                    'objectId'     => $entity->getId(),
427
                                ]
428
                            ),
429
                        ]
430
                    );
431
432
                    if ($form->get('buttons')->get('save')->isClicked()) {
433
                        $returnUrl = $this->generateUrl('mautic_company_index', $viewParameters);
434
                        $template  = 'MauticLeadBundle:Company:index';
435
                    }
436
                }
437
            } else {
438
                //unlock the entity
439
                $model->unlockEntity($entity);
440
441
                $returnUrl = $this->generateUrl('mautic_company_index', $viewParameters);
442
                $template  = 'MauticLeadBundle:Company:index';
443
            }
444
445
            $passthrough = [
446
                'activeLink'    => '#mautic_company_index',
447
                'mauticContent' => 'company',
448
            ];
449
450
            // Check to see if this is a popup
451
            if (!empty($form['updateSelect'])) {
452
                $template    = false;
453
                $passthrough = array_merge(
454
                    $passthrough,
455
                    [
456
                        'updateSelect' => $form['updateSelect']->getData(),
457
                        'id'           => $entity->getId(),
458
                        'name'         => $entity->getName(),
459
                    ]
460
                );
461
            }
462
463
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
464
                return $this->postActionRedirect(
465
                    [
466
                        'returnUrl'       => $returnUrl,
467
                        'viewParameters'  => $viewParameters,
468
                        'contentTemplate' => $template,
469
                        'passthroughVars' => $passthrough,
470
                    ]
471
                );
472
            } elseif ($valid) {
473
                // Refetch and recreate the form in order to populate data manipulated in the entity itself
474
                $company = $model->getEntity($objectId);
475
                $form    = $model->createForm($company, $this->get('form.factory'), $action, ['fields' => $fields, 'update_select' => $updateSelect]);
476
            }
477
        } else {
478
            //lock the entity
479
            $model->lockEntity($entity);
480
        }
481
482
        $fields = $model->organizeFieldsByGroup($fields);
483
        $groups = array_keys($fields);
484
        sort($groups);
485
        $template = 'MauticLeadBundle:Company:form_'.($this->request->get('modal', false) ? 'embedded' : 'standalone').'.html.php';
486
487
        return $this->delegateView(
488
            [
489
                'viewParameters' => [
490
                    'tmpl'   => $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index',
491
                    'entity' => $entity,
492
                    'form'   => $form->createView(),
493
                    'fields' => $fields,
494
                    'groups' => $groups,
495
                ],
496
                'contentTemplate' => $template,
497
                'passthroughVars' => [
498
                    'activeLink'    => '#mautic_company_index',
499
                    'mauticContent' => 'company',
500
                    'updateSelect'  => InputHelper::clean($this->request->query->get('updateSelect')),
501
                    'route'         => $this->generateUrl(
502
                        'mautic_company_action',
503
                        [
504
                            'objectAction' => 'edit',
505
                            'objectId'     => $entity->getId(),
506
                        ]
507
                    ),
508
                ],
509
            ]
510
        );
511
    }
512
513
    /**
514
     * Loads a specific company into the detailed panel.
515
     *
516
     * @param $objectId
517
     *
518
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
519
     */
520
    public function viewAction($objectId)
521
    {
522
        /** @var \Mautic\LeadBundle\Model\CompanyModel $model */
523
        $model  = $this->getModel('lead.company');
524
525
        // When we change company data these changes get cached
526
        // so we need to clear the entity manager
527
        $model->getRepository()->clear();
528
529
        /** @var \Mautic\LeadBundle\Entity\Company $company */
530
        $company = $model->getEntity($objectId);
531
532
        //set some permissions
533
        $permissions = $this->get('mautic.security')->isGranted(
534
            [
535
                'lead:leads:viewown',
536
                'lead:leads:viewother',
537
                'lead:leads:create',
538
                'lead:leads:editown',
539
                'lead:leads:editother',
540
                'lead:leads:deleteown',
541
                'lead:leads:deleteother',
542
            ],
543
            'RETURN_ARRAY'
544
        );
545
546
        //set the return URL
547
        $returnUrl = $this->generateUrl('mautic_company_index');
548
549
        $postActionVars = [
550
            'returnUrl'       => $returnUrl,
551
            'contentTemplate' => 'MauticLeadBundle:Company:index',
552
            'passthroughVars' => [
553
                'activeLink'    => '#mautic_company_index',
554
                'mauticContent' => 'company',
555
            ],
556
        ];
557
558
        if (null === $company) {
559
            return $this->postActionRedirect(
560
                array_merge(
561
                    $postActionVars,
562
                    [
563
                        'flashes' => [
564
                            [
565
                                'type'    => 'error',
566
                                'msg'     => 'mautic.company.error.notfound',
567
                                'msgVars' => ['%id%' => $objectId],
568
                            ],
569
                        ],
570
                    ]
571
                )
572
            );
573
        }
574
575
        if (!$this->get('mautic.security')->hasEntityAccess(
576
            'lead:leads:viewown',
577
            'lead:leads:viewother',
578
            $company->getPermissionUser()
579
        )
580
        ) {
581
            return $this->accessDenied();
582
        }
583
584
        $fields         = $company->getFields();
585
        $companiesRepo  = $model->getCompanyLeadRepository();
586
        $contacts       = $companiesRepo->getCompanyLeads($objectId);
587
588
        $leadsIds = 'ids:';
589
        foreach ($contacts as $contact) {
590
            $leadsIds .= $contact['lead_id'].',';
591
        }
592
        $leadsIds = substr($leadsIds, 0, -1);
593
594
        $engagementData = is_array($contacts) ? $this->getCompanyEngagementsForGraph($contacts) : [];
595
596
        $contacts = $this->getCompanyContacts($objectId, null, $leadsIds);
597
598
        return $this->delegateView(
599
            [
600
                'viewParameters' => [
601
                    'company'           => $company,
602
                    'fields'            => $fields,
603
                    'items'             => $contacts['items'],
604
                    'permissions'       => $permissions,
605
                    'engagementData'    => $engagementData,
606
                    'security'          => $this->get('mautic.security'),
607
                    'page'              => $contacts['page'],
608
                    'totalItems'        => $contacts['count'],
609
                    'limit'             => $contacts['limit'],
610
                ],
611
                'contentTemplate' => 'MauticLeadBundle:Company:company.html.php',
612
            ]
613
        );
614
    }
615
616
    /**
617
     * Get company's contacts for company view.
618
     *
619
     * @param int    $companyId
620
     * @param int    $page
621
     * @param string $leadsIds  filter to get only company's contacts
622
     *
623
     * @return array
624
     */
625
    public function getCompanyContacts($companyId, $page = 0, $leadsIds = '')
626
    {
627
        $this->setListFilters();
628
629
        /** @var \Mautic\LeadBundle\Model\LeadModel $model */
630
        $model   = $this->getModel('lead');
631
        $session = $this->get('session');
632
        //set limits
633
        $limit = $session->get('mautic.company.'.$companyId.'.contacts.limit', $this->get('mautic.helper.core_parameters')->get('default_pagelimit'));
634
        $start = (1 === $page) ? 0 : (($page - 1) * $limit);
635
        if ($start < 0) {
636
            $start = 0;
637
        }
638
639
        //do some default filtering
640
        $orderBy    = $session->get('mautic.company.'.$companyId.'.contacts.orderby', 'l.last_active');
641
        $orderByDir = $session->get('mautic.company.'.$companyId.'.contacts.orderbydir', 'DESC');
642
643
        $results = $model->getEntities([
644
            'start'          => $start,
645
            'limit'          => $limit,
646
            'filter'         => ['string' => $leadsIds],
647
            'orderBy'        => $orderBy,
648
            'orderByDir'     => $orderByDir,
649
            'withTotalCount' => true,
650
        ]);
651
652
        $count = $results['count'];
653
        unset($results['count']);
654
655
        $leads = $results['results'];
656
        unset($results);
657
658
        return [
659
            'items' => $leads,
660
            'page'  => $page,
661
            'count' => $count,
662
            'limit' => $limit,
663
        ];
664
    }
665
666
    /**
667
     * Clone an entity.
668
     *
669
     * @param int $objectId
670
     *
671
     * @return array|JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
672
     */
673
    public function cloneAction($objectId)
674
    {
675
        $model  = $this->getModel('lead.company');
676
        $entity = $model->getEntity($objectId);
677
678
        if (null != $entity) {
679
            if (!$this->get('mautic.security')->isGranted('lead:leads:create')) {
680
                return $this->accessDenied();
681
            }
682
683
            $entity = clone $entity;
684
        }
685
686
        return $this->newAction($entity);
687
    }
688
689
    /**
690
     * Deletes the entity.
691
     *
692
     * @param int $objectId
693
     *
694
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
695
     */
696
    public function deleteAction($objectId)
697
    {
698
        $page      = $this->get('session')->get('mautic.company.page', 1);
699
        $returnUrl = $this->generateUrl('mautic_company_index', ['page' => $page]);
700
        $flashes   = [];
701
702
        $postActionVars = [
703
            'returnUrl'       => $returnUrl,
704
            'viewParameters'  => ['page' => $page],
705
            'contentTemplate' => 'MauticLeadBundle:Company:index',
706
            'passthroughVars' => [
707
                'activeLink'    => '#mautic_company_index',
708
                'mauticContent' => 'company',
709
            ],
710
        ];
711
712
        if ('POST' == $this->request->getMethod()) {
713
            $model  = $this->getModel('lead.company');
714
            $entity = $model->getEntity($objectId);
715
716
            if (null === $entity) {
717
                $flashes[] = [
718
                    'type'    => 'error',
719
                    'msg'     => 'mautic.company.error.notfound',
720
                    'msgVars' => ['%id%' => $objectId],
721
                ];
722
            } elseif (!$this->get('mautic.security')->isGranted('lead:leads:deleteother')) {
723
                return $this->accessDenied();
724
            } elseif ($model->isLocked($entity)) {
725
                return $this->isLocked($postActionVars, $entity, 'lead.company');
726
            }
727
728
            $model->deleteEntity($entity);
729
730
            $flashes[] = [
731
                'type'    => 'notice',
732
                'msg'     => 'mautic.core.notice.deleted',
733
                'msgVars' => [
734
                    '%name%' => $entity->getName(),
735
                    '%id%'   => $objectId,
736
                ],
737
            ];
738
        } //else don't do anything
739
740
        return $this->postActionRedirect(
741
            array_merge(
742
                $postActionVars,
743
                [
744
                    'flashes' => $flashes,
745
                ]
746
            )
747
        );
748
    }
749
750
    /**
751
     * Deletes a group of entities.
752
     *
753
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
754
     */
755
    public function batchDeleteAction()
756
    {
757
        $page      = $this->get('session')->get('mautic.company.page', 1);
758
        $returnUrl = $this->generateUrl('mautic_company_index', ['page' => $page]);
759
        $flashes   = [];
760
761
        $postActionVars = [
762
            'returnUrl'       => $returnUrl,
763
            'viewParameters'  => ['page' => $page],
764
            'contentTemplate' => 'MauticLeadBundle:Company:index',
765
            'passthroughVars' => [
766
                'activeLink'    => '#mautic_company_index',
767
                'mauticContent' => 'company',
768
            ],
769
        ];
770
771
        if ('POST' == $this->request->getMethod()) {
772
            $model     = $this->getModel('lead.company');
773
            $ids       = json_decode($this->request->query->get('ids', '{}'));
774
            $deleteIds = [];
775
776
            // Loop over the IDs to perform access checks pre-delete
777
            foreach ($ids as $objectId) {
778
                $entity = $model->getEntity($objectId);
779
780
                if (null === $entity) {
781
                    $flashes[] = [
782
                        'type'    => 'error',
783
                        'msg'     => 'mautic.company.error.notfound',
784
                        'msgVars' => ['%id%' => $objectId],
785
                    ];
786
                } elseif (!$this->get('mautic.security')->isGranted('lead:leads:deleteother')) {
787
                    $flashes[] = $this->accessDenied(true);
788
                } elseif ($model->isLocked($entity)) {
789
                    $flashes[] = $this->isLocked($postActionVars, $entity, 'lead.company', true);
790
                } else {
791
                    $deleteIds[] = $objectId;
792
                }
793
            }
794
795
            // Delete everything we are able to
796
            if (!empty($deleteIds)) {
797
                $entities = $model->deleteEntities($deleteIds);
798
                $deleted  = count($entities);
799
                $this->addFlash(
800
                    'mautic.company.notice.batch_deleted',
801
                    [
802
                        'pluralCount' => $deleted,
803
                        '%count%'     => $deleted,
804
                    ]
805
                );
806
            }
807
        } //else don't do anything
808
809
        return $this->postActionRedirect(
810
            array_merge(
811
                $postActionVars,
812
                [
813
                    'flashes' => $flashes,
814
                ]
815
            )
816
        );
817
    }
818
819
    /**
820
     * Company Merge function.
821
     *
822
     * @param $objectId
823
     *
824
     * @return array|JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
825
     */
826
    public function mergeAction($objectId)
827
    {
828
        //set some permissions
829
        $permissions = $this->get('mautic.security')->isGranted(
830
            [
831
                'lead:leads:viewother',
832
                'lead:leads:create',
833
                'lead:leads:editother',
834
                'lead:leads:deleteother',
835
            ],
836
            'RETURN_ARRAY'
837
        );
838
        /** @var \Mautic\LeadBundle\Model\CompanyModel $model */
839
        $model            = $this->getModel('lead.company');
840
        $secondaryCompany = $model->getEntity($objectId);
841
        $page             = $this->get('session')->get('mautic.lead.page', 1);
842
843
        //set the return URL
844
        $returnUrl = $this->generateUrl('mautic_company_index', ['page' => $page]);
845
846
        $postActionVars = [
847
            'returnUrl'       => $returnUrl,
848
            'viewParameters'  => ['page' => $page],
849
            'contentTemplate' => 'MauticLeadBundle:Company:index',
850
            'passthroughVars' => [
851
                'activeLink'    => '#mautic_company_index',
852
                'mauticContent' => 'company',
853
            ],
854
        ];
855
856
        if (null === $secondaryCompany) {
857
            return $this->postActionRedirect(
858
                array_merge(
859
                    $postActionVars,
860
                    [
861
                        'flashes' => [
862
                            [
863
                                'type'    => 'error',
864
                                'msg'     => 'mautic.lead.company.error.notfound',
865
                                'msgVars' => ['%id%' => $objectId],
866
                            ],
867
                        ],
868
                    ]
869
                )
870
            );
871
        }
872
873
        $action = $this->generateUrl('mautic_company_action', ['objectAction' => 'merge', 'objectId' => $secondaryCompany->getId()]);
874
875
        $form = $this->get('form.factory')->create(
876
            CompanyMergeType::class,
877
            [],
878
            [
879
                'action'      => $action,
880
                'main_entity' => $secondaryCompany->getId(),
881
            ]
882
        );
883
884
        if ('POST' == $this->request->getMethod()) {
885
            $valid = true;
886
            if (!$this->isFormCancelled($form)) {
887
                if ($valid = $this->isFormValid($form)) {
888
                    $data           = $form->getData();
889
                    $primaryMergeId = $data['company_to_merge'];
890
                    $primaryCompany = $model->getEntity($primaryMergeId);
891
892
                    if (null === $primaryCompany) {
893
                        return $this->postActionRedirect(
894
                            array_merge(
895
                                $postActionVars,
896
                                [
897
                                    'flashes' => [
898
                                        [
899
                                            'type'    => 'error',
900
                                            'msg'     => 'mautic.lead.company.error.notfound',
901
                                            'msgVars' => ['%id%' => $primaryCompany->getId()],
902
                                        ],
903
                                    ],
904
                                ]
905
                            )
906
                        );
907
                    } elseif (!$permissions['lead:leads:editother']) {
908
                        return $this->accessDenied();
909
                    } elseif ($model->isLocked($secondaryCompany)) {
910
                        //deny access if the entity is locked
911
                        return $this->isLocked($postActionVars, $primaryCompany, 'lead.company');
912
                    } elseif ($model->isLocked($primaryCompany)) {
913
                        //deny access if the entity is locked
914
                        return $this->isLocked($postActionVars, $primaryCompany, 'lead.company');
915
                    }
916
917
                    //Both leads are good so now we merge them
918
                    $mainCompany = $model->companyMerge($primaryCompany, $secondaryCompany, false);
919
                }
920
921
                if ($valid) {
922
                    $viewParameters = [
923
                        'objectId'     => $primaryCompany->getId(),
924
                        'objectAction' => 'edit',
925
                    ];
926
                }
927
            } else {
928
                $viewParameters = [
929
                    'objectId'     => $secondaryCompany->getId(),
930
                    'objectAction' => 'edit',
931
                ];
932
            }
933
934
            return $this->postActionRedirect(
935
                [
936
                    'returnUrl'       => $this->generateUrl('mautic_company_action', $viewParameters),
937
                    'viewParameters'  => $viewParameters,
938
                    'contentTemplate' => 'MauticLeadBundle:Company:edit',
939
                    'passthroughVars' => [
940
                        'closeModal' => 1,
941
                    ],
942
                ]
943
            );
944
        }
945
946
        $tmpl = $this->request->get('tmpl', 'index');
947
948
        return $this->delegateView(
949
            [
950
                'viewParameters' => [
951
                    'tmpl'         => $tmpl,
952
                    'action'       => $action,
953
                    'form'         => $form->createView(),
954
                    'currentRoute' => $this->generateUrl(
955
                        'mautic_company_action',
956
                        [
957
                            'objectAction' => 'merge',
958
                            'objectId'     => $secondaryCompany->getId(),
959
                        ]
960
                    ),
961
                ],
962
                'contentTemplate' => 'MauticLeadBundle:Company:merge.html.php',
963
                'passthroughVars' => [
964
                    'route'  => false,
965
                    'target' => ('update' == $tmpl) ? '.company-merge-options' : null,
966
                ],
967
            ]
968
        );
969
    }
970
971
    /**
972
     * Export company's data.
973
     *
974
     * @param $companyId
975
     *
976
     * @return array|JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\StreamedResponse
977
     */
978
    public function companyExportAction($companyId)
979
    {
980
        //set some permissions
981
        $permissions = $this->get('mautic.security')->isGranted(
982
            [
983
                'lead:leads:viewown',
984
                'lead:leads:viewother',
985
            ],
986
            'RETURN_ARRAY'
987
        );
988
989
        if (!$permissions['lead:leads:viewown'] && !$permissions['lead:leads:viewother']) {
990
            return $this->accessDenied();
991
        }
992
993
        /** @var companyModel $companyModel */
994
        $companyModel  = $this->getModel('lead.company');
995
        $company       = $companyModel->getEntity($companyId);
996
        $dataType      = $this->request->get('filetype', 'csv');
997
998
        if (empty($company)) {
999
            return $this->notFound();
1000
        }
1001
1002
        $companyFields = $company->getProfileFields();
1003
        $export        = [];
1004
        foreach ($companyFields as $alias=>$companyField) {
1005
            $export[] = [
1006
                'alias' => $alias,
1007
                'value' => $companyField,
1008
            ];
1009
        }
1010
1011
        return $this->exportResultsAs($export, $dataType, 'company_data_'.($companyFields['companyemail'] ?: $companyFields['id']));
1012
    }
1013
}
1014