Example #1
0
 /**
  * @param Channel $channel
  */
 public function scheduleRecalculation(Channel $channel = null)
 {
     if ($channel) {
         $isActiveChannel = $channel->getStatus() === Channel::STATUS_ACTIVE;
         $channelData = $channel->getData();
         $rfmEnabled = !empty($channelData[RFMAwareInterface::RFM_STATE_KEY]);
         if (!$isActiveChannel || !$rfmEnabled) {
             return;
         }
     }
     if ($this->getJob()) {
         return;
     }
     $args = [];
     if ($channel) {
         $argument = sprintf('--channel=%s', $channel->getId());
         $channelJob = $this->getJob($argument);
         if ($channelJob) {
             return;
         }
         $args = [$argument];
     }
     $job = new Job(CalculateAnalyticsCommand::COMMAND_NAME, $args);
     $em = $this->doctrineHelper->getEntityManager($job);
     if (!$channel) {
         $channelJobs = $this->getJob('--channel');
         if ($channelJobs) {
             foreach ($channelJobs as $channelJob) {
                 $em->remove($channelJob);
             }
         }
     }
     $em->persist($job);
     $em->flush($job);
 }
Example #2
0
 /**
  * @return array
  */
 public function testPostLead()
 {
     $request = ["lead" => ['name' => 'lead_name_' . mt_rand(1, 500), 'firstName' => 'first_name_' . mt_rand(1, 500), 'lastName' => 'last_name_' . mt_rand(1, 500), 'owner' => '1', 'dataChannel' => self::$dataChannel->getId()]];
     $this->client->request('POST', $this->getUrl('oro_api_post_lead'), $request);
     $result = $this->getJsonResponseContent($this->client->getResponse(), 201);
     $request['id'] = $result['id'];
     return $request;
 }
Example #3
0
 /**
  * @return array
  */
 public function testCreateB2bCustomer()
 {
     $request = ['b2bcustomer' => ['name' => 'b2bcustomer_name_' . mt_rand(1, 500), 'account' => $this->getReference('default_account')->getId(), 'owner' => '1', 'dataChannel' => self::$dataChannel->getId(), 'shippingAddress' => $this->testAddress]];
     $this->client->request('POST', $this->getUrl('oro_api_post_b2bcustomer'), $request);
     $result = $this->getJsonResponseContent($this->client->getResponse(), 201);
     $request['id'] = $result['id'];
     return $request;
 }
 public function testPostSubmit()
 {
     $data = new Channel();
     $data->setChannelType(self::TEST_CHANNEL_TYPE);
     $form = $this->getMock('Symfony\\Component\\Form\\Test\\FormInterface');
     $event = new FormEvent($form, $data);
     $this->subscriber->postSubmit($event);
     $this->assertEquals(self::TEST_CUSTOMER_IDENTITY, $data->getCustomerIdentity());
 }
 /**
  * @param Channel $channel
  */
 protected function validateCustomerIdentity(Channel $channel)
 {
     $errorLabel = 'orocrm.channel.form.customer_identity_selected_not_correctly.label';
     $fieldName = 'customerIdentity';
     $entities = $channel->getEntities();
     if (!in_array($channel->getCustomerIdentity(), $entities)) {
         $this->context->addViolationAt($fieldName, $errorLabel);
     }
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     $this->em = $manager;
     $date = new \DateTime('now');
     $channel = new Channel();
     $channel->setName('some name')->setOwner($this->loadOwner())->setChannelType('testType')->setCreatedAt($date)->setUpdatedAt($date)->setCustomerIdentity('test1')->setEntities(['test1', 'test2']);
     $manager->persist($channel);
     $this->setReference('default_channel', $channel);
     $manager->flush();
 }
 protected function prepareEvent()
 {
     $this->entity->setEntities(['OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity1', 'OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity2']);
     $this->event->expects($this->atLeastOnce())->method('getChannel')->will($this->returnValue($this->entity));
     $this->settingProvider->expects($this->at(0))->method('getIntegrationConnectorName')->with('OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity1')->will($this->returnValue('TestConnector1'));
     $this->settingProvider->expects($this->at(1))->method('getIntegrationConnectorName')->with('OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity2')->will($this->returnValue('TestConnector2'));
     $this->registry->expects($this->any())->method('getManager')->will($this->returnValue($this->em));
     $this->em->expects($this->once())->method('persist')->with($this->integration);
     $this->em->expects($this->once())->method('flush');
 }
Example #8
0
 /**
  * @param Channel $channel
  */
 protected function handleRequestChannelType(Channel &$channel)
 {
     if ($channel->getChannelType()) {
         return;
     }
     $channelType = $this->request->get(sprintf('%s[channelType]', ChannelType::NAME), null, true);
     if (!$channelType) {
         return;
     }
     $channel->setChannelType($channelType);
 }
Example #9
0
 /**
  * @param Channel $entity
  *
  * @return bool
  */
 public function isApplicable($entity)
 {
     if (!$entity instanceof Channel) {
         return false;
     }
     $customerIdentity = $entity->getCustomerIdentity();
     if (empty($customerIdentity)) {
         return false;
     }
     return in_array($this->interface, class_implements($customerIdentity), true);
 }
 /**
  * @param Channel $channel
  */
 protected function validateIntegration(Channel $channel)
 {
     $errorLabel = 'orocrm.channel.form.integration_invalid.label';
     $field = 'dataSource';
     $integrationType = $this->provider->getIntegrationType($channel->getChannelType());
     if (!empty($integrationType)) {
         $integration = $channel->getDataSource();
         if (empty($integration)) {
             $this->context->addViolationAt($field, $errorLabel);
         }
     }
 }
 /**
  * @dataProvider dataProvider
  */
 public function testOnChannelStatusChange($status, $isEnabled)
 {
     $integration = new Integration();
     $entity = new Channel();
     $entity->setStatus($status);
     $entity->setDataSource($integration);
     $this->registry->expects($this->any())->method('getManager')->will($this->returnValue($this->em));
     $this->em->expects($this->once())->method('persist')->with($integration);
     $this->em->expects($this->once())->method('flush');
     $listener = new ChangeChannelStatusListener($this->registry);
     $listener->onChannelStatusChange(new ChannelChangeStatusEvent($entity));
     $this->assertEquals($integration->getEnabled(), $isEnabled);
 }
 public function testOnChannelSucceedSave()
 {
     $this->entity->setEntities(['OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity1', 'OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity2']);
     $this->event->expects($this->once())->method('getChannel')->will($this->returnValue($this->entity));
     $this->settingProvider->expects($this->at(0))->method('getIntegrationConnectorName')->with('OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity1')->will($this->returnValue('TestConnector1'));
     $this->settingProvider->expects($this->at(1))->method('getIntegrationConnectorName')->with('OroCRM\\Bundle\\AcmeBundle\\Entity\\TestEntity2')->will($this->returnValue('TestConnector2'));
     $this->registry->expects($this->any())->method('getManager')->will($this->returnValue($this->em));
     $this->em->expects($this->once())->method('persist')->with($this->integration);
     $this->em->expects($this->once())->method('flush');
     $channelSaveSucceedListener = new ChannelSaveSucceedListener($this->settingProvider, $this->registry);
     $channelSaveSucceedListener->onChannelSucceedSave($this->event);
     $this->assertEquals($this->integration->getConnectors(), ['TestConnector1', 'TestConnector2']);
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     $this->em = $manager;
     $date = new \DateTime('now');
     $channel = new Channel();
     $channel->setName('first channel')->setStatus(true)->setOwner($this->loadOwner())->setChannelType('testType')->setCreatedAt($date)->setUpdatedAt($date)->setCustomerIdentity('test1')->setEntities(['test1', 'test2']);
     $manager->persist($channel);
     $this->setReference('channel_1', $channel);
     $channel2 = new Channel();
     $channel2->setName('second channel')->setOwner($this->loadOwner())->setChannelType('testType')->setCreatedAt($date)->setUpdatedAt($date)->setCustomerIdentity('test1')->setEntities(['OroCRM\\Bundle\\ChannelBundle\\Entity\\CustomerIdentity']);
     $manager->persist($channel2);
     $this->setReference('channel_2', $channel2);
     $manager->flush();
 }
Example #14
0
 public function testCreate()
 {
     $crawler = $this->client->request('GET', $this->getUrl('orocrm_sales_b2bcustomer_create'));
     $form = $crawler->selectButton('Save and Close')->form();
     $name = 'name' . $this->generateRandomString();
     $form['orocrm_sales_b2bcustomer_form[name]'] = $name;
     $form['orocrm_sales_b2bcustomer_form[account]'] = self::$account->getId();
     $form['orocrm_sales_b2bcustomer_form[dataChannel]'] = self::$channel->getId();
     $form['orocrm_sales_b2bcustomer_form[owner]'] = 1;
     $this->client->followRedirects(true);
     $crawler = $this->client->submit($form);
     $result = $this->client->getResponse();
     $this->assertHtmlResponseStatusCodeEquals($result, 200);
     $this->assertContains("Customer saved", $crawler->html());
 }
Example #15
0
 /**
  * @Route(
  *      "/status/change/{id}",
  *      requirements={"id"="\d+"},
  *      name="orocrm_channel_change_status"
  *  )
  * @AclAncestor("orocrm_channel_update")
  */
 public function changeStatusAction(Channel $channel)
 {
     if ($channel->getStatus() == Channel::STATUS_ACTIVE) {
         $message = 'orocrm.channel.controller.message.status.deactivated';
         $channel->setStatus(Channel::STATUS_INACTIVE);
     } else {
         $message = 'orocrm.channel.controller.message.status.activated';
         $channel->setStatus(Channel::STATUS_ACTIVE);
     }
     $this->getDoctrine()->getManager()->flush();
     $event = new ChannelChangeStatusEvent($channel);
     $this->get('event_dispatcher')->dispatch(ChannelChangeStatusEvent::EVENT_NAME, $event);
     $this->get('session')->getFlashBag()->add('success', $this->get('translator')->trans($message));
     return $this->redirect($this->generateUrl('orocrm_channel_view', ['id' => $channel->getId(), '_enableContentProviders' => 'mainMenu']));
 }
Example #16
0
 /**
  * Returns built channel
  *
  * @SuppressWarnings(PHPMD.NPathComplexity)
  *
  * @return Channel
  */
 public function getChannel()
 {
     $type = $this->getDefaultType();
     $name = $this->getDefaultName($type);
     $identity = $this->settingsProvider->getCustomerIdentityFromConfig($type);
     if ($this->populateEntities) {
         $this->entities = $this->settingsProvider->getEntitiesByChannelType($type);
     }
     $this->addEntity($identity, true);
     $owner = $this->owner;
     if (!$owner) {
         $owner = $this->getDefaultOrganization();
     }
     $this->channel->setChannelType($type);
     $this->channel->setName($name);
     $this->channel->setOwner($owner);
     $this->channel->setCustomerIdentity($identity);
     $this->channel->setEntities($this->entities);
     $this->channel->setStatus($this->status);
     $this->channel->setDataSource($this->dataSource);
     if (null !== $this->createdAt) {
         // set created at only whn not nullable, otherwise update scenario will fail
         $this->channel->setCreatedAt($this->createdAt);
     }
     return $this->channel;
 }
Example #17
0
 /**
  * @param string  $key
  * @param Channel $entity
  */
 public function fillEntityData($key, $entity)
 {
     list($name, $type) = explode('|', $key);
     $entity->setName($name);
     $entity->setChannelType($type);
     $entity->setStatus(Channel::STATUS_ACTIVE);
     $entity->setCreatedAt(new \DateTime());
     $entity->setUpdatedAt(new \DateTime());
 }
Example #18
0
 /**
  * @param ObjectManager $om
  */
 protected function persistDemoRFM(ObjectManager $om)
 {
     $rfmData = ['recency' => [['min' => null, 'max' => 7], ['min' => 7, 'max' => 30], ['min' => 30, 'max' => 90], ['min' => 90, 'max' => 365], ['min' => 365, 'max' => null]], 'frequency' => [['min' => 52, 'max' => null], ['min' => 12, 'max' => 52], ['min' => 4, 'max' => 12], ['min' => 2, 'max' => 4], ['min' => null, 'max' => 2]], 'monetary' => [['min' => 10000, 'max' => null], ['min' => 1000, 'max' => 10000], ['min' => 100, 'max' => 1000], ['min' => 10, 'max' => 100], ['min' => null, 'max' => 10]]];
     foreach ($rfmData as $type => $values) {
         foreach ($values as $idx => $limits) {
             $category = new RFMMetricCategory();
             $category->setCategoryIndex($idx + 1)->setChannel($this->dataChannel)->setCategoryType($type)->setMinValue($limits['min'])->setMaxValue($limits['max'])->setOwner($this->organization);
             $om->persist($category);
         }
     }
     $data = $this->dataChannel->getData();
     $data['rfm_enabled'] = true;
     $this->dataChannel->setData($data);
     $om->persist($this->dataChannel);
 }
Example #19
0
 /**
  * Returns built channel
  *
  * @SuppressWarnings(PHPMD.NPathComplexity)
  *
  * @return Channel
  */
 public function getChannel()
 {
     $type = $this->getDefaultType();
     $name = $this->getDefaultName($type);
     $identity = $this->settingsProvider->getCustomerIdentityFromConfig($type);
     if ($this->populateEntities) {
         $this->entities = $this->settingsProvider->getEntitiesByChannelType($type);
     }
     $this->addEntity($identity, true);
     $owner = $this->owner;
     if (!$owner) {
         $owner = $this->getDefaultOrganization();
     }
     $this->channel->setChannelType($type);
     $this->channel->setName($name);
     $this->channel->setOwner($owner);
     $this->channel->setCustomerIdentity($identity);
     $this->channel->setEntities($this->entities);
     $this->channel->setStatus($this->status);
     $this->channel->setDataSource($this->dataSource);
     return $this->channel;
 }
Example #20
0
 /**
  * @param Channel $channel
  * @param array   $entitiesToAdd
  */
 protected function addEntitiesToChannel(Channel $channel, array $entitiesToAdd)
 {
     $entities = $channel->getEntities();
     $entities = is_array($entities) ? $entities : [];
     $combinedEntities = array_unique(array_merge($entities, $entitiesToAdd));
     $channel->setEntities($combinedEntities);
 }
 /**
  * @param Channel $channel
  * @param array   $ids
  *
  * @return BufferedQueryResultIterator|CustomerIdentity[]
  */
 protected function getEntitiesByChannel(Channel $channel, array $ids = [])
 {
     $entityFQCN = $channel->getCustomerIdentity();
     $qb = $this->getDoctrineHelper()->getEntityRepository($entityFQCN)->createQueryBuilder('e');
     $qb->orderBy(sprintf('e.%s', $this->getDoctrineHelper()->getSingleEntityIdentifierFieldName($entityFQCN)));
     $qb->andWhere('e.dataChannel = :dataChannel');
     $qb->setParameter('dataChannel', $channel);
     if ($ids) {
         $qb->andWhere($qb->expr()->in('e.id', ':ids'));
         $qb->setParameter('ids', $ids);
     }
     $iterator = new BufferedQueryResultIterator($qb);
     // !!! should be the same as flush batch, will not work otherwise because of detached entities after EM#clear()
     $iterator->setBufferSize(self::BATCH_SIZE);
     return $iterator;
 }
    /**
     * @param Channel   $channel
     * @param \DateTime $date Datetime object in system timezone
     *
     * @return float
     */
    private function getAggregatedValue(Channel $channel, \DateTime $date)
    {
        $sql = <<<SQL
  SELECT AVG(h.{amount})
  FROM {tableName} h
  JOIN(
    SELECT MAX(h1.{id}) as identity
    FROM {tableName} h1
    WHERE h1.{dataChannel} = :channelId AND h1.{createdAt} <= :endDate
    GROUP BY h1.{account}
  ) maxres ON maxres.identity = h.{id}
SQL;
        $sqlNames = $this->getSQLColumnNamesArray();
        $sql = preg_replace_callback('/{(\\w+)}/', function ($matches) use($sqlNames) {
            $fieldName = trim(end($matches));
            if (isset($sqlNames[$fieldName])) {
                return $sqlNames[$fieldName];
            }
            throw new \RuntimeException(sprintf('Entity does not have field named "%s"', $fieldName));
        }, $sql);
        $calculationPeriodEnd = Carbon::instance($date);
        $calculationPeriodEnd->firstOfMonth();
        $calculationPeriodEnd->addMonth();
        return $this->getEntityManager()->getConnection()->executeQuery($sql, ['channelId' => $channel->getId(), 'endDate' => $calculationPeriodEnd], ['channelId' => Type::INTEGER, 'endDate' => Type::DATETIME])->fetchColumn(0);
    }
 /**
  * @param int[]   $accountIds
  * @param Channel $channel
  * @param string  $customerIdentity
  * @param string  $lifetimeFieldName
  */
 private function updateLifetime(array $accountIds, Channel $channel, $customerIdentity, $lifetimeFieldName)
 {
     $customerMetadata = $this->em->getClassMetadata($customerIdentity);
     $lifetimeColumnName = $customerMetadata->getColumnName($lifetimeFieldName);
     $this->em->getConnection()->executeUpdate('UPDATE orocrm_channel_lifetime_hist SET status = :status
          WHERE data_channel_id = :channel_id AND account_id IN (:account_ids)', ['status' => false, 'channel_id' => $channel->getId(), 'account_ids' => $accountIds], ['status' => Type::BOOLEAN, 'channel_id' => Type::INTEGER, 'account_ids' => Connection::PARAM_INT_ARRAY]);
     $this->em->getConnection()->executeUpdate('INSERT INTO orocrm_channel_lifetime_hist' . ' (account_id, data_channel_id, status, amount, created_at)' . sprintf(' SELECT e.account_id AS hist_account_id, e.data_channel_id AS hist_data_channel_id,' . ' e.account_id > 0 as hist_status, SUM(COALESCE(e.%s, 0)) AS hist_amount,' . ' TIMESTAMP :created_at AS hist_created_at', $lifetimeColumnName) . sprintf(' FROM %s AS e', $customerMetadata->getTableName()) . ' WHERE e.data_channel_id = :channel_id AND e.account_id IN (:account_ids)' . ' GROUP BY hist_account_id, hist_data_channel_id, hist_status, hist_created_at', ['created_at' => new \DateTime(null, new \DateTimeZone('UTC')), 'channel_id' => $channel->getId(), 'account_ids' => $accountIds], ['created_at' => Type::DATETIME, 'channel_id' => Type::INTEGER, 'account_ids' => Connection::PARAM_INT_ARRAY]);
 }
Example #24
0
 /**
  * @return array
  */
 public function handleRequestDataProvider()
 {
     $channel = new Channel();
     $channel->setChannelType('existing_type');
     return ['has type' => [$channel, null, 'existing_type'], 'has not request value' => [$channel, null, 'existing_type'], 'has request value' => [new Channel(), 'some_type', 'some_type']];
 }
Example #25
0
 /**
  * @param Channel $channel
  * @param array $ids
  * @return \ArrayIterator|BufferedQueryResultIterator
  */
 protected function getEntityIdsByChannel(Channel $channel, array $ids = [])
 {
     $entityFQCN = $channel->getCustomerIdentity();
     $qb = $this->doctrineHelper->getEntityRepository($entityFQCN)->createQueryBuilder('e');
     $metadata = $this->doctrineHelper->getEntityMetadataForClass($entityFQCN);
     $metrics = [];
     foreach ($this->providers as $provider) {
         if ($provider->supports($channel) && $metadata->hasField($provider->getType())) {
             $metrics[] = $provider->getType();
         }
     }
     if (count($metrics) === 0) {
         return new \ArrayIterator();
     }
     $idField = sprintf('e.%s', $this->doctrineHelper->getSingleEntityIdentifierFieldName($entityFQCN));
     $qb->select(preg_filter('/^/', 'e.', $metrics))->addSelect($idField . ' as id')->where('e.dataChannel = :dataChannel')->orderBy($qb->expr()->asc($idField))->setParameter('dataChannel', $channel);
     if (count($ids) !== 0) {
         $qb->andWhere($qb->expr()->in($idField, ':ids'))->setParameter('ids', $ids);
     }
     return (new BufferedQueryResultIterator($qb))->setBufferSize(self::BATCH_SIZE);
 }
 /**
  * {@inheritdoc}
  */
 public function supports(Channel $channel)
 {
     $entityFQCN = $channel->getCustomerIdentity();
     return is_a($entityFQCN, 'OroCRM\\Bundle\\AnalyticsBundle\\Model\\RFMAwareInterface', true) && is_a($entityFQCN, 'OroCRM\\Bundle\\ChannelBundle\\Model\\CustomerIdentityInterface', true) && is_a($entityFQCN, $this->className, true);
 }
Example #27
0
 /**
  * @param Channel $channel
  *
  * @return bool
  */
 protected function isApplicable(Channel $channel = null)
 {
     if (!$channel) {
         return false;
     }
     $customerIdentity = $channel->getCustomerIdentity();
     if (!$customerIdentity) {
         return false;
     }
     return in_array($this->interface, class_implements($customerIdentity), true);
 }
 public function testIsApplicableVisitEventNonMagentoChannel()
 {
     $this->extendConfigProvider->expects($this->once())->method('hasConfig')->willReturn(true);
     $visitEvent = new TrackingVisitEvent();
     $visit = new TrackingVisit();
     $visitEvent->setVisit($visit);
     $channel = new Channel();
     $channel->setChannelType('test');
     $website = new TestTrackingWebsite();
     $website->setChannel($channel);
     $visit->setTrackingWebsite($website);
     $this->assertFalse($this->provider->isApplicableVisitEvent($visitEvent));
 }