Issues (3627)

bundles/PluginBundle/Command/FetchLeadsCommand.php (1 issue)

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\PluginBundle\Command;
13
14
use Mautic\PluginBundle\Integration\UnifiedIntegrationInterface;
15
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
16
use Symfony\Component\Console\Input\InputInterface;
17
use Symfony\Component\Console\Input\InputOption;
18
use Symfony\Component\Console\Output\OutputInterface;
19
20
/**
21
 * Class FetchLeadsCommand.
22
 */
23
class FetchLeadsCommand extends ContainerAwareCommand
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    protected function configure()
29
    {
30
        $this
31
            ->setName('mautic:integration:fetchleads')
32
            ->setAliases(
33
                [
34
                    'mautic:integration:synccontacts',
35
                ]
36
            )
37
            ->setDescription('Fetch leads from integration.')
38
            ->addOption(
39
                '--integration',
40
                '-i',
41
                InputOption::VALUE_REQUIRED,
42
                'Fetch leads from integration. Integration must be enabled and authorised.',
43
                null
44
            )
45
            ->addOption('--start-date', '-d', InputOption::VALUE_REQUIRED, 'Set start date for updated values.')
46
            ->addOption(
47
                '--end-date',
48
                '-t',
49
                InputOption::VALUE_REQUIRED,
50
                'Set end date for updated values.'
51
            )
52
            ->addOption(
53
                '--fetch-all',
54
                null,
55
                InputOption::VALUE_NONE,
56
                'Get all CRM contacts whatever the date is. Should be used at instance initialization only'
57
            )
58
            ->addOption(
59
                '--time-interval',
60
                '-a',
61
                InputOption::VALUE_OPTIONAL,
62
                'Send time interval to check updates on Salesforce, it should be a correct php formatted time interval in the past eg:(10 minutes)'
63
            )
64
            ->addOption(
65
                '--limit',
66
                '-l',
67
                InputOption::VALUE_OPTIONAL,
68
                'Number of records to process when syncing objects',
69
                100
70
            )
71
            ->addOption('--force', '-f', InputOption::VALUE_NONE, 'Force execution even if another process is assumed running.');
72
73
        parent::configure();
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    protected function execute(InputInterface $input, OutputInterface $output)
80
    {
81
        $container = $this->getContainer();
82
83
        $translator    = $container->get('translator');
84
        $integration   = $input->getOption('integration');
85
        $startDate     = $input->getOption('start-date');
86
        $endDate       = $input->getOption('end-date');
87
        $interval      = $input->getOption('time-interval');
88
        $limit         = $input->getOption('limit');
89
        $fetchAll      = $input->getOption('fetch-all');
90
        $leadsExecuted = $contactsExecuted = null;
91
92
        // @TODO Since integration is mandatory it should really be turned into an agument, but that would not be B.C.
93
        if (!$integration) {
94
            throw new \RuntimeException('An integration must be specified');
95
        }
96
97
        $integrationHelper = $container->get('mautic.helper.integration');
98
99
        $integrationObject = $integrationHelper->getIntegrationObject($integration);
100
        if (!$integrationObject instanceof UnifiedIntegrationInterface) {
101
            $availableIntegrations = array_filter($integrationHelper->getIntegrationObjects(),
102
                function (UnifiedIntegrationInterface $availableIntegration) {
103
                    return $availableIntegration->isConfigured();
104
                });
105
            throw new \RuntimeException(sprintf('The Integration "%s" is not one of the available integrations (%s)', $integration, implode(', ', array_keys($availableIntegrations))));
106
        }
107
108
        if (!$interval) {
109
            $interval = '15 minutes';
110
        }
111
        $startDate = !$startDate ? date('c', strtotime('-'.$interval)) : date('c', strtotime($startDate));
112
        $endDate   = !$endDate ? date('c') : date('c', strtotime($endDate));
113
114
        if (!$startDate || !$endDate) {
115
            $output->writeln(sprintf('<info>Invalid date rage given %s -> %s</info>', $startDate, $endDate));
116
117
            return 255;
118
        }
119
120
        /** @var \Mautic\PluginBundle\Helper\IntegrationHelper $integrationHelper */
121
        $integrationHelper = $container->get('mautic.helper.integration');
122
123
        $integrationObject = $integrationHelper->getIntegrationObject($integration);
124
125
        if (!$integrationObject->isAuthorized()) {
126
            $output->writeln(sprintf('<error>ERROR:</error> <info>'.$translator->trans('mautic.plugin.command.notauthorized').'</info>', $integration));
127
128
            return 255;
129
        }
130
131
        // Tell audit log to use integration name
132
        define('MAUTIC_AUDITLOG_USER', $integration);
133
134
        $config            = $integrationObject->mergeConfigToFeatureSettings();
135
        $supportedFeatures = $integrationObject->getIntegrationSettings()->getSupportedFeatures();
136
137
        defined('MAUTIC_CONSOLE_VERBOSITY') or define('MAUTIC_CONSOLE_VERBOSITY', $output->getVerbosity());
138
139
        if (!isset($config['objects'])) {
140
            $config['objects'] = [];
141
        }
142
143
        $params['start']    = $startDate;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = array(); before regardless.
Loading history...
144
        $params['end']      = $endDate;
145
        $params['limit']    = $limit;
146
        $params['fetchAll'] = $fetchAll;
147
        $params['output']   = $output;
148
149
        $integrationObject->setCommandParameters($params);
150
151
        // set this constant to ensure that all contacts have the same date modified time and date synced time to prevent a pull/push loop
152
        define('MAUTIC_DATE_MODIFIED_OVERRIDE', time());
153
154
        if (isset($supportedFeatures) && in_array('get_leads', $supportedFeatures)) {
155
            if (null !== $integrationObject && method_exists($integrationObject, 'getLeads') && isset($config['objects'])) {
156
                $output->writeln('<info>'.$translator->trans('mautic.plugin.command.fetch.leads', ['%integration%' => $integration]).'</info>');
157
                $output->writeln('<comment>'.$translator->trans('mautic.plugin.command.fetch.leads.starting').'</comment>');
158
159
                //Handle case when integration object are named "Contacts" and "Leads"
160
                $leadObjectName = 'Lead';
161
                if (in_array('Leads', $config['objects'])) {
162
                    $leadObjectName = 'Leads';
163
                }
164
                $contactObjectName = 'Contact';
165
                if (in_array(strtolower('Contacts'), array_map(function ($i) {
166
                    return strtolower($i);
167
                }, $config['objects']), true)) {
168
                    $contactObjectName = 'Contacts';
169
                }
170
171
                $updated = $created = $processed = 0;
172
                if (in_array($leadObjectName, $config['objects'])) {
173
                    $leadList = [];
174
                    $results  = $integrationObject->getLeads($params, null, $leadsExecuted, $leadList, $leadObjectName);
175
                    if (is_array($results)) {
176
                        list($justUpdated, $justCreated) = $results;
177
                        $updated += (int) $justUpdated;
178
                        $created += (int) $justCreated;
179
                    } else {
180
                        $processed += (int) $results;
181
                    }
182
                }
183
                if (in_array(strtolower($contactObjectName), array_map(function ($i) {
184
                    return strtolower($i);
185
                }, $config['objects']), true)) {
186
                    $output->writeln('');
187
                    $output->writeln('<comment>'.$translator->trans('mautic.plugin.command.fetch.contacts.starting').'</comment>');
188
                    $contactList = [];
189
                    $results     = $integrationObject->getLeads($params, null, $contactsExecuted, $contactList, $contactObjectName);
190
                    if (is_array($results)) {
191
                        list($justUpdated, $justCreated) = $results;
192
                        $updated += (int) $justUpdated;
193
                        $created += (int) $justCreated;
194
                    } else {
195
                        $processed += (int) $results;
196
                    }
197
                }
198
199
                $output->writeln('');
200
201
                if ($processed) {
202
                    $output->writeln(
203
                        '<comment>'.$translator->trans('mautic.plugin.command.fetch.leads.events_executed', ['%events%' => $processed])
204
                        .'</comment>'."\n"
205
                    );
206
                } else {
207
                    $output->writeln(
208
                        '<comment>'.$translator->trans(
209
                            'mautic.plugin.command.fetch.leads.events_executed_breakout',
210
                            ['%updated%' => $updated, '%created%' => $created]
211
                        )
212
                        .'</comment>'."\n"
213
                    );
214
                }
215
            }
216
217
            if (null !== $integrationObject && method_exists($integrationObject, 'getCompanies') && isset($config['objects'])
218
                && in_array(
219
                    'company',
220
                    $config['objects']
221
                )
222
            ) {
223
                $updated = $created = $processed = 0;
224
                $output->writeln('<info>'.$translator->trans('mautic.plugin.command.fetch.companies', ['%integration%' => $integration]).'</info>');
225
                $output->writeln('<comment>'.$translator->trans('mautic.plugin.command.fetch.companies.starting').'</comment>');
226
227
                $results = $integrationObject->getCompanies($params);
228
                if (is_array($results)) {
229
                    list($justUpdated, $justCreated) = $results;
230
                    $updated += (int) $justUpdated;
231
                    $created += (int) $justCreated;
232
                } else {
233
                    $processed += (int) $results;
234
                }
235
                $output->writeln('');
236
                if ($processed) {
237
                    $output->writeln(
238
                        '<comment>'.$translator->trans('mautic.plugin.command.fetch.companies.events_executed', ['%events%' => $processed])
239
                        .'</comment>'."\n"
240
                    );
241
                } else {
242
                    $output->writeln(
243
                        '<comment>'.$translator->trans(
244
                            'mautic.plugin.command.fetch.companies.events_executed_breakout',
245
                            ['%updated%' => $updated, '%created%' => $created]
246
                        )
247
                        .'</comment>'."\n"
248
                    );
249
                }
250
            }
251
        }
252
253
        if (isset($supportedFeatures) && in_array('push_leads', $supportedFeatures) && method_exists($integrationObject, 'pushLeads')) {
254
            $output->writeln('<info>'.$translator->trans('mautic.plugin.command.pushing.leads', ['%integration%' => $integration]).'</info>');
255
            $result  = $integrationObject->pushLeads($params);
256
            $ignored = 0;
257
258
            if (4 === count($result)) {
259
                list($updated, $created, $errored, $ignored) = $result;
260
            } elseif (3 === count($result)) {
261
                list($updated, $created, $errored) = $result;
262
            } else {
263
                $errored                 = '?';
264
                list($updated, $created) = $result;
265
            }
266
            $output->writeln(
267
                '<comment>'.$translator->trans(
268
                    'mautic.plugin.command.fetch.pushing.leads.events_executed',
269
                    [
270
                        '%updated%' => $updated,
271
                        '%created%' => $created,
272
                        '%errored%' => $errored,
273
                        '%ignored%' => $ignored,
274
                    ]
275
                )
276
                .'</comment>'."\n"
277
            );
278
279
            if (method_exists($integrationObject, 'pushCompanies')) {
280
                $output->writeln('<info>'.$translator->trans('mautic.plugin.command.pushing.companies', ['%integration%' => $integration]).'</info>');
281
                $result  = $integrationObject->pushCompanies($params);
282
                $ignored = 0;
283
284
                if (4 === count($result)) {
285
                    list($updated, $created, $errored, $ignored) = $result;
286
                } elseif (3 === count($result)) {
287
                    list($updated, $created, $errored) = $result;
288
                } else {
289
                    $errored                 = '?';
290
                    list($updated, $created) = $result;
291
                }
292
                $output->writeln(
293
                    '<comment>'.$translator->trans(
294
                        'mautic.plugin.command.fetch.pushing.companies.events_executed',
295
                        [
296
                            '%updated%' => $updated,
297
                            '%created%' => $created,
298
                            '%errored%' => $errored,
299
                            '%ignored%' => $ignored,
300
                        ]
301
                    )
302
                    .'</comment>'."\n"
303
                );
304
            }
305
        }
306
307
        return 0;
308
    }
309
}
310