PageRenderTime 49ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/app/bundles/PluginBundle/Command/FetchLeadsCommand.php

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