deveau-a
1/2/2018 - 1:12 PM

ProgressBar with php/twig

ProgressBar with php/twig

public function profitAction(Request $request)
    {
        $form = $this->createForm(new SettingProfitType);
 
        $form->handleRequest($request);
 
        if ($_POST) {
            $operation = $_POST['operation'];
            $percent = (float)$_POST['percent'];
            $product = $_POST['product'];
            $attribute = $_POST['attribute'];
            $round = $_POST['round'];
            $errors_form = '';
            $rm = $this->get('clever_rest.resource_manager');
 
            if($product == 'false')
                $product = false;
            else
                $product = true;
 
            if($attribute == 'false')
                $attribute = false;
            else
                $attribute = true;
 
            if(!$operation && !$percent)
                $errors_form = 'No operation and no percent informed';
            elseif(!$operation)
                $errors_form = 'No operation selected';
            elseif(!$percent)
                $errors_form = 'No percent informed';
            elseif(!is_float($percent) && !is_int($percent))
                $errors_form = 'Percent must be a number';
 
            if($errors_form)
                echo 'error'.$errors_form.'error';
 
            if($percent && $percent!=0 && $operation)
            {
                if($operation == 'add')
                    $sign = (1+$percent/100);
                else
                    $sign = (1-$percent/100);
 
                $response = new StreamedResponse();
                $response->headers->add([
                    //'Content-type' => 'text/plain',
                    //'Transfer-Encoding' => 'chunked'
                ]);
                $response->setCallback(function () use($rm, $product, $attribute, $sign, $round) {
 
                    $totalCountProducts = 0;
                    $totalCountAttributes = 0;
                    if ($product) {
                        $totalCountProducts = $rm->getManager()->getRepository('CleverErpBundle:Product')->countList(['deleted' => false]);
                    }
                    if ($attribute) {
                        $totalCountAttributes = $rm->getManager()->getRepository('CleverErpBundle:ProductAttribute')->countAllPriceNotNull();
                    }
 
                    $totalEntities = $totalCountProducts+$totalCountAttributes;
                    $count = 0;
                    $flushEach = 100;
 
                    if ($product) {
                        $pageNumber = 1;
                        $totalCount = $rm->getManager()->getRepository('CleverErpBundle:Product')->countList(['deleted' => false]);
                        $basePageCount = round($totalCount / $flushEach, 0, PHP_ROUND_HALF_UP);
                        $totalPageCount = $basePageCount;
                        for ($i = 0; $i < $totalPageCount; $i++) {
                            $entities = $rm->getManager()->getRepository('CleverErpBundle:Product')
                                ->getList($pageNumber, $flushEach, ['deleted' => false])->getQuery()->getResult();
                            $this->updatePricesEntities($pageNumber, $flushEach, $count, $totalEntities, $sign, $round, $entities);
                            flush();
                            ob_flush();
                        }
                    }
 
                    if ($attribute) {
                        $pageNumber = 1;
                        $totalCount = $rm->getManager()->getRepository('CleverErpBundle:ProductAttribute')->countAllPriceNotNull();
                        $basePageCount = round($totalCount / $flushEach, 0, PHP_ROUND_HALF_UP);
                        $totalPageCount = $basePageCount;
                        for ($i = 0; $i < $totalPageCount; $i++) {
                            $productAttributes = $rm->getManager()->getRepository('CleverErpBundle:ProductAttribute')
                                ->findAllPriceNotNull($pageNumber, $flushEach)->getQuery()->getResult();
                            $this->updatePricesEntities($pageNumber, $flushEach, $count, $totalEntities, $sign, $round, $productAttributes);
                            flush();
                            ob_flush();
                        }
                    }
                    $rm->flush();
                });
                $response->setStatusCode(200);
                $response->send();
                return $response;
            }
        }
 
        return $this->render('CleverErpBundle:Setting:profit.html.twig', array(
            'form' => $form->createView()));
    }
 
    private function updatePricesEntities(&$pageNumber, $flushEach, &$count, $totalEntities, $sign, $round, $entities)
    {
        $rm = $this->get('clever_rest.resource_manager');
 
        foreach($entities as $entity)
        {
            $count++;
 
            $entity->setPriceTe($this->roundPrice($entity->getPriceTe()*$sign,$round));
            $entity->setPriceTi($this->roundPrice($entity->getPriceTi()*$sign,$round));
            $rm->update($entity,false);
 
            if($count % round($flushEach / 10, 0) === 0)
                echo "sep".(round($count/$totalEntities*100)).str_repeat(' ', 4096).PHP_EOL;
        }
        echo "sep".(round($count/$totalEntities*100)).str_repeat(' ', 4096).PHP_EOL;
        $rm->flush();
        $rm->getManager()->clear();
        unset($entities);
 
        $pageNumber++;
    }
keyboard_arrow_right
<script type="text/javascript">
		$('#validateButton').on('click',function(e){
		  e.preventDefault();
		  var operation = $('#clever_erpbundle_setting_profit_operation').val();
		  var percent = $('#clever_erpbundle_setting_profit_percent').val();
		  var round = $('#clever_erpbundle_setting_profit_round').val();
		  var product = $('.form_clever_erpbundle_setting_profit_product .bootstrap-switch-container input').prop('checked');
		  var attribute = $('.form_clever_erpbundle_setting_profit_attribute .bootstrap-switch-container input').prop('checked');
          var data = new FormData();
          data.append('operation', operation);
          data.append('percent', percent);
          data.append('round', round);
          data.append('product', product);
          data.append('attribute', attribute);
          var xhr = new XMLHttpRequest();
          xhr.open('POST', Routing.generate('settings_profit'), true);
          xhr.send(data);
          var timer;
          timer = window.setInterval(function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
              window.clearTimeout(timer);
            }
            var text = xhr.responseText;
            error = text.split('error');
            if(error[1])
            {
              $('.alert-infos').html('<i class="icon-info22"></i>'+Translator.trans(error[1]));
              $('#progress').addClass('hidden');
            }
            else
            {
              text = text.split('sep');
              text = parseInt(text[text.length - 1]);
              if(isNaN(text))
                text = 0;
              var elem = $('#progressBar');
              var label = $('#progressBarLabel');
              var progress = $('#progress');
              progress.removeClass('hidden');
              elem.css('width','0');
              elem.css('width',text + '%');
              if(parseInt(text)>50)
                label.css('color','white');
              else
                label.css('color','black');
              label.text(text + '%');
              $('.alert-infos').html('<i class="icon-info22"></i>'+"{{ infos_form }}");
              if(parseInt(text)==100)
              {
                $.toast({
                  heading: Translator.trans('General profit'),
                  text: Translator.trans('General profit has successfully been updated'),
                  type: 'success',
                  showHideTransition: 'slide',
                  icon: 'success',
                  position: 'bottom-right',
                  stack: false
                });
              }
            }
          }, 100);
		})
	</script>