コード例 #1
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $cronLog = new CronLog();
     $cronLog->setStartAt(new \DateTime());
     $cronLog->setDescription('Cusres email check');
     $cronLog->setScript('hp:cusres-email-check');
     $this->_em = $this->getContainer()->get('doctrine')->getManager();
     $mailServer = $this->getContainer()->get('app_core.mailsender');
     /**
      * @var ImapService $imap
      */
     $imap = $this->getContainer()->get('app_core.imap');
     $messages = $imap->getMessages('Inbox/Alta/Notifications/HP/Released', null, ImapService::F_UNFLAGGED);
     foreach ($messages as $message) {
         if (false !== strstr($message->getMessageBody(), 'Решение по товарам принято')) {
             if (false !== strstr($message->getMessageBody(), 'ВЫПУСК ТОВАРОВ')) {
                 preg_match('#([0-9]{8}\\/[0-9]{6}\\/[0-9]{7})#', $message->getMessageBody(), $dt);
                 if (isset($dt[0]) && strlen($dt[0])) {
                     $gtdNumber = $dt[0];
                     //1. Проверяем отправлялся ли кусрес
                     $json = json_decode(file_get_contents($this->_umbrellaApi . '&method=get_cusres_date&params=' . $gtdNumber));
                     if (false == $json->success) {
                         $params = $mailServer->getSubscriptionParams('HPCUSRES');
                         $body = preg_replace('/#DOCUMENT_NUM#/', $gtdNumber, $params['body']);
                         $subject = "CUSRES#{$gtdNumber} did't send";
                         $mailServer->sendEmail($params['subscribers']['to'], $subject, $body);
                     }
                     //2. Проверяем совпадают ли инвойсы
                     if (false !== ($invoices = strstr($message->getMessageBody(), 'Инвойс'))) {
                         preg_match('#.*Инвойс:(.*)#', $message->getMessageBody(), $matches);
                         $json = json_decode(file_get_contents($this->_umbrellaApi . '&method=get_invoices_by_gtd&params=' . $gtdNumber));
                         if (true == $json->success) {
                             $jsonInvoices = $json->result;
                             $invoices = array_map('trim', explode(',', $matches[1]));
                             $error = [];
                             foreach ($invoices as $inv) {
                                 if (!in_array($inv, $jsonInvoices)) {
                                     $error[] = "Иновойс:{$inv}";
                                 }
                             }
                             if (!empty($error)) {
                                 $params = $mailServer->getSubscriptionParams('HPINVOICE');
                                 $body = preg_replace(['/#DOCUMENT_NUM#/', '/#INVOICE#/'], [$gtdNumber, implode('\\n\\r', $error)], $params['body']);
                                 $subject = "Inovices did't find at CUSRES#{$gtdNumber} ";
                                 $mailServer->sendEmail($params['subscribers']['to'], $subject, $body);
                             }
                         }
                     }
                 }
             }
             $message->setFlag(ImapService::F_FLAGGED);
             $message->setFlag(ImapService::F_SEEN);
         } else {
             continue;
         }
     }
 }
コード例 #2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $cronLog = new CronLog();
     $cronLog->setStartAt(new DateTime());
     $cronLog->setDescription('Process SCA log files');
     $cronLog->setScript('spm:process-sca-logs');
     $this->_em = $this->getContainer()->get('doctrine')->getManager();
     /**
      * @var ImapService $imap
      */
     $imap = $this->getContainer()->get('app_core.imap');
     $messages = $imap->getMessages('Inbox/Sportmaster/SCA', null, ImapService::F_UNFLAGGED);
     foreach ($messages as $message) {
         if (!$message->getAttachments()) {
             continue;
         }
         foreach ($message->getAttachments() as $attachment) {
             $savePath = UploadAbstract::getUploadDir('sportmaster');
             if (($savedFile = $attachment->saveToDirectory($savePath)) == true) {
                 $importService = new ImportSpmInterfaceLog($savePath . DIRECTORY_SEPARATOR . $attachment->getFileName(), $this->getContainer());
                 $importService->parse();
             }
         }
         $message->setFlag(ImapService::F_FLAGGED);
         $message->setFlag(ImapService::F_SEEN);
     }
     $cronLog->setEndAt(new DateTime());
     $this->_em->persist($cronLog);
     $this->_em->flush();
     $this->_em->clear();
     $output->writeln('Completed');
 }
コード例 #3
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $cronLog = new CronLog();
     $cronLog->setStartAt(new \DateTime());
     $cronLog->setDescription('Update currency rates');
     $cronLog->setScript('core:rate');
     $this->_container = $this->getContainer();
     $this->_doctrine = $this->_container->get('doctrine');
     $this->_em = $this->_container->get('doctrine')->getManager();
     $url = $input->getOption('from');
     $client = new GuzzleHttp\Client(['timeout' => 0, 'allow_redirects' => false, 'proxy' => 'http://*****:*****@wsproxy.corp.panorg.com:8080']);
     $request = $client->get($url);
     $response = $request->getBody();
     $xml = new \DOMDocument('1.0', 'utf-8');
     $xml->loadXML($response);
     $repoCurrency = $this->_doctrine->getRepository('CoreBundle:Currency');
     $rateDate = $xml->getElementsByTagName('ValCurs')->item(0)->attributes->getNamedItem('Date')->nodeValue;
     $rubCurrency = $repoCurrency->findOneBy(['codeAlpha3' => self::CHAR_CODE_RUB]);
     foreach ($xml->getElementsByTagName('Valute') as $valute) {
         $charCode = $valute->getElementsByTagName('CharCode')->item(0)->nodeValue;
         if ($charCode == 'EUR' || $charCode == 'USD') {
             $currencyTo = $repoCurrency->findOneBy(['codeAlpha3' => $charCode]);
             if (($currencyRate = $this->isCurrencyRateExist($currencyTo, new \DateTime($rateDate))) == false) {
                 $currencyRate = new Entity\CurrencyRate();
             }
             $rate = $valute->getElementsByTagName('Value')->item(0)->nodeValue;
             $currencyRate->setCurrencyFrom($rubCurrency);
             $currencyRate->setCurrencyTo($currencyTo);
             $currencyRate->setRate(str_replace(',', '.', $rate));
             $currencyRate->setRateDate(new \DateTime($rateDate));
             $currencyRate->setSource($url);
             $this->_em->persist($currencyRate);
         }
     }
     $cronLog->setEndAt(new \DateTime());
     $this->_em->persist($cronLog);
     $this->_em->flush();
     $this->_em->clear();
     die('Completed');
 }
コード例 #4
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $cronLog = new CronLog();
     $cronLog->setStartAt(new DateTime());
     $cronLog->setScript('spm:report');
     $this->_em = $this->getContainer()->get('doctrine')->getManager();
     switch ($input->getArgument('name')) {
         case 'sca-failed-events':
             $cronLog->setDescription('Produce SCA Failed Events report');
             $report = new FailedEventsReport($this->getContainer());
             $report->sendEmail();
             $this->getContainer()->get('swiftmailer.command.spool_send')->run(new ArgvInput(array()), new ConsoleOutput());
             break;
         default:
             $output->writeln('Please specify the report name. Here are available reports: ');
             $output->writeln('1. sca-failed-events');
             break;
     }
     $cronLog->setEndAt(new DateTime());
     $this->_em->persist($cronLog);
     $this->_em->flush();
     $this->_em->clear();
     $output->writeln('Completed');
 }
コード例 #5
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->_em = $this->getContainer()->get('doctrine')->getManager();
     $this->sportmaster = $this->_em->getRepository('CoreBundle:Customer')->findOneBy(['abbr' => $this->getContainer()->getParameter('sportmaster_abbr')]);
     if ($this->getContainer()->getParameter("kernel.environment") == 'prod') {
         $dsn = 'mysql:dbname=MOW-sportmaster;host=ch13x100.europe.panorg.com:3307';
         $user = '******';
         $password = '******';
     } else {
         $dsn = 'mysql:dbname=MOW-sportmaster;host=mowns003:3306';
         $user = '******';
         $password = '******';
     }
     $this->pdo = new \PDO($dsn, $user, $password);
     $cronLog = new CronLog();
     $cronLog->setStartAt(new DateTime());
     $cronLog->setDescription($this->getDescription());
     $cronLog->setScript($this->getName());
     $queryAll = "SELECT * FROM container c WHERE trim(Name) != '' AND ShippingLine != 18";
     if ($input->getOption('type') == self::FETCH_TYPE_DAILY) {
         $queryAll .= $this->dailyCondition;
     }
     $stmt = $this->pdo->prepare($queryAll);
     $stmt->execute();
     $mappingType = [];
     $mappingType[1] = $this->_em->getRepository('CoreBundle:ContainerType')->findOneBy(['isoCode' => '22G0']);
     $mappingType[2] = $this->_em->getRepository('CoreBundle:ContainerType')->findOneBy(['isoCode' => '42G0']);
     $mappingType[3] = $this->_em->getRepository('CoreBundle:ContainerType')->findOneBy(['isoCode' => '45G0']);
     $validator = new Validator\ValidatorContainerNumber();
     $processed = [];
     $m = memory_get_usage(true);
     $i = 0;
     try {
         while (($row = $stmt->fetch(\PDO::FETCH_ASSOC)) == true) {
             if (!isset($processed[strtolower($row['Name'])])) {
                 if ($validator->validate($row['Name'])) {
                     $containerType = isset($mappingType[$row['ContainerType']]) ? $mappingType[$row['ContainerType']] : null;
                     $container = $this->_em->getRepository('CoreBundle:Container')->findOneBy(['name' => $row['Name']]);
                     if (!$container) {
                         $container = new \App\CoreBundle\Entity\Container();
                         $container->setName($row['Name'])->setContainerType($containerType);
                         $this->_em->persist($container);
                         $i++;
                         if ($i % self::BATCH_SIZE == 0) {
                             $this->_em->flush();
                             //                        $this->_em->clear();
                         }
                     }
                     $processed[strtolower($container->getName())] = 1;
                 } else {
                     $this->messageService->addMessage("Container name = {$row['Name']} is invalid, skipping", Message::ERROR);
                 }
             }
         }
         $output->writeln("New Containers: {$i}");
         $this->_em->flush();
         $this->syncContainerWithoutAta($input->getOption('type'));
     } catch (NonUniqueResultException $e) {
         $this->messageService->addMessage("Not unique entity {$e->getMessage()} {$e->getFile()} {$e->getLine()}", Message::ERROR);
     } catch (\Exception $e) {
         $this->messageService->addMessage("Fatal exception: {$e->getMessage()} {$e->getFile()} {$e->getLine()}", Message::ERROR);
     }
     if ($this->messageService->hasCategory(Message::ERROR)) {
         $message = \Swift_Message::newInstance()->setSubject('Sync container errors')->setFrom('*****@*****.**')->setTo(['*****@*****.**', '*****@*****.**'])->setBody($this->messageService->dumpAsHtml(), 'text/html');
         $this->getContainer()->get('mailer')->send($message);
         $this->getContainer()->get('swiftmailer.command.spool_send')->run(new ArgvInput(array()), new ConsoleOutput());
     }
     $cronLog->setEndAt(new DateTime());
     $this->_em->persist($cronLog);
     $this->_em->flush();
     $output->writeln('memory: ' . (memory_get_usage(true) - $m));
     $output->writeln('Completed');
 }
コード例 #6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->_em = $this->getContainer()->get('doctrine')->getManager();
     $cronLog = new CronLog();
     $cronLog->setStartAt(new DateTime());
     $cronLog->setDescription($this->getDescription());
     $cronLog->setScript($this->getName());
     $qb = $this->_em->getRepository('CoreBundle:ContainerFlow')->createQueryBuilder('cf');
     /**
      * @var ContainerFlow[] $flows
      */
     $flows = $qb->innerJoin('cf.subcontractor', 'sub')->innerJoin('cf.container', 'container')->where('sub.code IN (:maersk, :cma, :fesco, :hmm, :apl) AND cf.ata IS NULL AND (cf.customDate1 IS NULL OR cf.customDate1 != :now)')->setMaxResults(self::SINGLE_FETCH)->setParameter('maersk', self::MAERSK_CODE)->setParameter('cma', self::CMA_CODE)->setParameter('fesco', self::FESCO_CODE)->setParameter('hmm', self::HMM_CODE)->setParameter('apl', self::APL_CODE)->setParameter('now', date('Y-m-d'))->getQuery()->getResult();
     foreach ($flows as $flow) {
         $parser = $this->getParserForCarrier($flow->getSubcontactor()->getCode());
         $classParts = explode('\\', get_class($parser));
         $service = array_pop($classParts);
         try {
             $result = $parser->getData($flow->getContainer()->getName());
             //try to find by bill of landing for CmaCgm & HMM
             if (is_null($result) && in_array($service, ['CmaCgm', 'HMM', 'MaerskClassic'])) {
                 $mbl = '';
                 foreach ($flow->getShipments() as $shipment) {
                     $mbl = $shipment->getMbl();
                     if ($mbl) {
                         $result = $parser->getData($mbl, ExternalTruckingAbstract::SEARCH_BOL);
                         break;
                     }
                 }
             }
             if ($result) {
                 if ($result->getBillOfLanding()) {
                     $this->checkMBL($result->getBillOfLanding(), $flow);
                 }
                 if ($result->getEta()) {
                     $flow->setETA(new DateTime($result->getEta()));
                 }
                 if ($result->getAta()) {
                     $flow->setATA(new DateTime($result->getAta()));
                 }
                 if ($result->getLoadOnVesselAt()) {
                     $flow->setLoadOnVesselAt(new DateTime($result->getLoadOnVesselAt()));
                 }
                 foreach ($result->getEvents() as $event) {
                     $vehicle = $this->addVehicle($event->getVessel(), $flow->getSubcontactor());
                     $flowEvent = $this->_em->getRepository('CoreBundle:ContainerFlowEvent')->findOneBy(['containerFlow' => $flow->getId(), 'details' => $event->getStatus(), 'locationDetails' => $event->getLocation(), 'occurredAt' => new DateTime($event->getDate())]);
                     if (!$flowEvent) {
                         $flowEvent = new ContainerFlowEvent();
                         $flowEvent->setContainerFlow($flow);
                     }
                     $flowEvent->setDetails(strtolower($event->getStatus()));
                     $flowEvent->setLocationDetails($event->getLocation());
                     $flowEvent->setOccurredAt(new DateTime($event->getDate()));
                     $flowEvent->setVehicle($vehicle);
                     $flowEvent->setVoyage($event->getVoyage());
                     $this->_em->persist($flowEvent);
                     $this->_em->flush();
                 }
             } else {
                 $this->messageService->addMessage("Service {$service}: Container data not found for {$flow->getContainer()->getName()}", Message::ERROR);
             }
         } catch (\Exception $e) {
             $this->messageService->addMessage("Service {$service}, container {$flow->getContainer()->getName()}: {$e->getMessage()}; file {$e->getFile()}; line {$e->getLine()}", Message::ERROR);
         }
         //set date of last check, next check will be tomorrow
         $flow->setCustomDate1(new DateTime('now'));
         $this->_em->persist($flow);
         $this->_em->flush();
     }
     if ($this->messageService->hasCategory(Message::ERROR)) {
         $message = \Swift_Message::newInstance()->setSubject('Container flow external trucking update')->setFrom('*****@*****.**')->setTo(['*****@*****.**', '*****@*****.**'])->setBody($this->messageService->dumpAsHtml(), 'text/html');
         $this->getContainer()->get('mailer')->send($message);
         $this->getContainer()->get('swiftmailer.command.spool_send')->run(new ArgvInput(array()), new ConsoleOutput());
     }
     $cronLog->setEndAt(new DateTime());
     $this->_em->persist($cronLog);
     $this->_em->flush();
     $output->writeln('Completed');
 }