src/ApplicationBundle/Controller/InventoryController.php line 8480

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Controller;
  3. use ApplicationBundle\Constants\AccountsConstant;
  4. use ApplicationBundle\Constants\GeneralConstant;
  5. use ApplicationBundle\Constants\HumanResourceConstant;
  6. use ApplicationBundle\Constants\InventoryConstant;
  7. use ApplicationBundle\Constants\LabelConstant;
  8. use ApplicationBundle\Constants\UserConstants;
  9. use ApplicationBundle\Entity\Carton;
  10. use ApplicationBundle\Entity\InvItemInOut;
  11. use ApplicationBundle\Entity\StockReceivedNote;
  12. use ApplicationBundle\Entity\ProductByCode;
  13. use ApplicationBundle\Entity\StockReceivedNoteItem;
  14. use ApplicationBundle\Entity\ConsumptionType;
  15. use ApplicationBundle\Entity\LabelFormat;
  16. use ApplicationBundle\Entity\UnitType;
  17. use ApplicationBundle\Entity\EmployeeAttendance;
  18. use ApplicationBundle\Entity\EmployeeAttendanceLog;
  19. use ApplicationBundle\Modules\Sales\Client;
  20. use ApplicationBundle\Modules\User\Users;
  21. use ApplicationBundle\Constants\ProjectConstant;
  22. use ApplicationBundle\Interfaces\SessionCheckInterface;
  23. use ApplicationBundle\Entity\InvProductCategories;
  24. use ApplicationBundle\Helper\Generic;
  25. use ApplicationBundle\Modules\Accounts\Accounts;
  26. use ApplicationBundle\Modules\Inventory\Inventory;
  27. use ApplicationBundle\Modules\Purchase\Purchase;
  28. use ApplicationBundle\Modules\Sales\SalesOrderM;
  29. use ApplicationBundle\Modules\Production\ProductionM;
  30. use ApplicationBundle\Modules\System\System;
  31. use ApplicationBundle\Modules\HumanResource\HumanResource;
  32. use ApplicationBundle\Modules\Purchase\Supplier;
  33. use ApplicationBundle\Modules\System\DeleteDocument;
  34. use ApplicationBundle\Modules\System\DocValidation;
  35. use ApplicationBundle\Modules\System\MiscActions;
  36. use ApplicationBundle\Modules\User\Company;
  37. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  38. use Symfony\Component\HttpFoundation\JsonResponse;
  39. use Symfony\Component\HttpFoundation\Request;
  40. use Symfony\Component\HttpFoundation\Response;
  41. class InventoryController extends GenericController implements SessionCheckInterface
  42. {
  43.     public function GetInitialDataForProductSelectVendorAppAction(Request $request)
  44.     {
  45.         $em $this->getDoctrine()->getManager();
  46.         $em_goc $this->getDoctrine()->getManager('company_group');
  47.         $session $request->getSession();
  48.         $companyId $this->getLoggedUserCompanyId($request);
  49.         $userRestrictions = [];
  50.         $selectiveDocumentsFlag 0;
  51.         $allowedLoginIds = [];
  52. //        $salesPersonList = Client::SalesPersonList($this->getDoctrine()->getManager());
  53. //
  54. //        $clientList = SalesOrderM::GetClientList($em, [], $companyId);
  55.         $userType $session->get(UserConstants::USER_TYPE);
  56.         $userId $session->get(UserConstants::USER_ID);
  57.         $productListArray = [];
  58.         $subCategoryListArray = [];
  59.         $categoryListArray = [];
  60.         $igListArray = [];
  61.         $unitListArray = [];
  62.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  63.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId);
  64.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  65.         $categoryList Inventory::ProductCategoryList($em$companyId);
  66.         $igList Inventory::ItemGroupList($em$companyId);
  67.         $unitList Inventory::UnitTypeList($em);
  68.         $brandList Inventory::GetBrandList($em$companyId);
  69.         $defaultSuffix 'lemon-o';
  70.         $pidsByCategory = [];
  71.         $pidsBySubCategory = [];
  72.         $pidsByIg = [];
  73.         $pidsByBrand = [];
  74.         foreach ($igList as $key => $product) {
  75.             if ($product['classSuffix'] == '') {
  76.                 $product['classSuffix'] = $defaultSuffix;
  77.                 $igList[$key]['classSuffix'] = $defaultSuffix;
  78.             }
  79.             $igListArray[] = $product;
  80.         }
  81.         foreach ($categoryList as $product) {
  82.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  83.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  84.             $categoryListArray[] = $product;
  85.         }
  86.         foreach ($subCategoryList as $product) {
  87.             if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
  88.                 $product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
  89.             $subCategoryListArray[] = $product;
  90.         }
  91.         foreach ($unitList as $product) {
  92.             $unitListArray[] = $product;
  93.         }
  94.         $brandListArray = [];
  95.         foreach ($brandList as $product) {
  96.             $brandListArray[] = $product;
  97.         }
  98.         foreach ($productList as $key => $product) {
  99. //            $productListArray[] = $product;
  100.             $product['igName'] = $igList[$product['igId']]['name'];
  101.             $product['categoryName'] = $categoryList[$product['categoryId']]['name'];
  102.             $product['subCategoryName'] = $subCategoryList[$product['subCategoryId']]['name'];
  103.             $product['brandName'] = $brandList[$product['brandCompany']]['name'];
  104.             $pidsByCategory[$product['categoryId']][] = $key;
  105.             $pidsBySubCategory[$product['subCategoryId']][] = $key;
  106.             $pidsIg[$product['igId']][] = $key;
  107.             $pidsByBrand[$product['brandCompany']][] = $key;
  108. //            $pidsBySubCategory=[];
  109. //            $pidsByIg=[];
  110.             $productListArray[] = $product;
  111.             $productList[$key] = $product;
  112.         }
  113.         $data = [
  114.             ''
  115.         ];
  116. //        if ($request->request->has('returnJson') || $request->query->has('returnJson'))
  117.         {
  118.             return new JsonResponse(
  119.                 array(
  120.                     'page_title' => ' ',
  121.                     'data' => $data,
  122.                     'productList' => $productList,
  123.                     'subCategoryList' => $subCategoryList,
  124.                     'categoryList' => $categoryList,
  125.                     'igList' => $igList,
  126.                     'unitList' => $unitList,
  127.                     'brandList' => $brandList,
  128.                     'productListArray' => $productListArray,
  129.                     'subCategoryListArray' => $subCategoryListArray,
  130.                     'categoryListArray' => $categoryListArray,
  131.                     'igListArray' => $igListArray,
  132.                     'unitListArray' => $unitListArray,
  133.                     'brandListArray' => $brandListArray,
  134.                     'pidsByCategory' => $pidsByCategory,
  135.                     'pidsBySubCategory' => $pidsBySubCategory,
  136.                     'pidsByBrand' => $pidsByBrand,
  137.                     'pidsByIg' => $pidsByIg,
  138.                     'success' => true
  139.                 )
  140.             );
  141.         }
  142.     }
  143.     public function GetRefreshedItemAction(Request $request$type 0)
  144.     {
  145.         $em $this->getDoctrine()->getManager();
  146.         $companyId $this->getLoggedUserCompanyId($request);
  147.         $productListArray = [];
  148.         $subCategoryListArray = [];
  149.         $categoryListArray = [];
  150.         $igListArray = [];
  151.         $unitListArray = [];
  152.         $skipProductList $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
  153.         $productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em$companyId$type);
  154.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  155.         $categoryList Inventory::ProductCategoryList($em$companyId);
  156.         $igList Inventory::ItemGroupList($em$companyId);
  157.         $unitList Inventory::UnitTypeList($em);
  158.         $brandList Inventory::GetBrandList($em$companyId);
  159.         foreach ($productList as $product) {
  160.             $productListArray[] = $product;
  161.         }
  162.         foreach ($categoryList as $product) {
  163.             $categoryListArray[] = $product;
  164.         }
  165.         foreach ($subCategoryList as $product) {
  166.             $subCategoryListArray[] = $product;
  167.         }
  168.         foreach ($igList as $product) {
  169.             $igListArray[] = $product;
  170.         }
  171.         foreach ($unitList as $product) {
  172.             $unitListArray[] = $product;
  173.         }
  174.         $brandListArray = [];
  175.         foreach ($brandList as $product) {
  176.             $brandListArray[] = $product;
  177.         }
  178.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  179.             "status" => GeneralConstant::ACTIVE,
  180.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  181. //            'type'=>1//trade items
  182.         ));
  183.         $sl = [];
  184.         $sl_array = [];
  185.         foreach ($qry as $product) {
  186.             $sl[$product->getServiceId()] = array(
  187.                 'text' => $product->getServiceName(),
  188.                 'value' => $product->getServiceId(),
  189.                 'name' => $product->getServiceName(),
  190.                 'id' => $product->getServiceId(),
  191.             );
  192.             $sl_array[] = array(
  193.                 'text' => $product->getServiceName(),
  194.                 'value' => $product->getServiceId(),
  195.                 'name' => $product->getServiceName(),
  196.                 'id' => $product->getServiceId(),
  197.             );
  198.         }
  199.         $hl Accounts::HeadList($em);
  200.         $hl_array Accounts::getParentLedgerHeads($em"""", [], 1$this->getLoggedUserCompanyId($request));
  201.         return new JsonResponse(
  202.             array(
  203. //                'page_title'=>'BOM',
  204. //                'clients'=>SalesOrderM::GetClientList($em),
  205. //                'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
  206.                 'productList' => $productList,
  207.                 'subCategoryList' => $subCategoryList,
  208.                 'categoryList' => $categoryList,
  209.                 'igList' => $igList,
  210.                 'unitList' => $unitList,
  211.                 'brandList' => $brandList,
  212.                 'productListArray' => $productListArray,
  213.                 'subCategoryListArray' => $subCategoryListArray,
  214.                 'categoryListArray' => $categoryListArray,
  215.                 'igListArray' => $igListArray,
  216.                 'unitListArray' => $unitListArray,
  217.                 'brandListArray' => $brandListArray,
  218.                 "success" => true,
  219.                 'users' => Users::getUserListById($em),
  220.                 'stages' => ProjectConstant::$projectStages,
  221.                 'sl' => $sl,
  222.                 'hl' => $hl,
  223.                 'hl_array' => $hl_array,
  224.                 'sl_array' => $sl_array,
  225. //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  226.             )
  227.         );
  228.     }
  229.     public function GetProductListForMisAction(Request $request)
  230.     {
  231.         $em $this->getDoctrine()->getManager();
  232.         $productIds $request->query->get('productId');
  233.         $fdmList = [];
  234.         $find_array = array('id' => $productIds);
  235.         if ($request->query->get('fdmList')) {
  236.             $find_array = array();
  237.             $fdmList $productIds $request->query->get('fdmList');
  238.         }
  239. //            $find_array=array('id' =>  $productIds);
  240.         $products $this->getDoctrine()
  241.             ->getRepository('ApplicationBundle:InvProducts')
  242.             ->findBy(
  243.                 $find_array
  244.             );
  245.         $productList = [];
  246.         $productListForShow = [];
  247.         foreach ($products as $entry) {
  248.             $productList[$entry->getId()] = array(
  249.                 'id' => $entry->getId(),
  250.                 'name' => $entry->getName(),
  251.                 'fdm' => $entry->getProductFdm(),
  252.             );
  253.         }
  254.         $products_in_stock $this->getDoctrine()
  255.             ->getRepository('ApplicationBundle:InventoryStorage')
  256.             ->findBy(
  257.                 $find_array
  258.             );
  259.         $warehouseList Inventory::WarehouseList($em);
  260.         if (!empty($fdmList)) {
  261.             foreach ($products_in_stock as $dt) {
  262. //            if()
  263.                 $matched_a_product 0;
  264.                 foreach ($fdmList as $fdm) {
  265.                     $matchFdm Inventory::MatchFdm($fdm$productList[$dt->getProductId()]['fdm']);
  266.                     if ($matchFdm['hasMatched'] == 1) {
  267.                         if ($matchFdm['isIdentical'] == || $matchFdm['FirstBelongsToSecond'] == 1) {
  268.                             $matched_a_product 1;
  269.                             if (isset($productListForShow[$dt->getProductId()])) {
  270.                             } else {
  271.                                 $productListForShow[$dt->getProductId()] = array(
  272.                                     'id' => $productList[$dt->getProductId()]['id'],
  273.                                     'name' => $productList[$dt->getProductId()]['name'],
  274.                                     'fdm' => $productList[$dt->getProductId()]['fdm'],
  275.                                 );
  276.                             }
  277.                             if (isset($productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  278.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  279.                             else {
  280.                                 $productListForShow[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  281.                             }
  282.                             break;
  283.                         }
  284.                     }
  285.                 }
  286.                 if ($matched_a_product == 0) {
  287.                     continue;
  288.                 }
  289.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  290.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  291.                 else
  292.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  293.             }
  294.         } else {
  295.             foreach ($products_in_stock as $dt) {
  296. //            if()
  297.                 if (isset($productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()]))
  298.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] += $dt->getQty();
  299.                 else
  300.                     $productList[$dt->getProductId()]['warehouse_' $dt->getWarehouseId()] = $dt->getQty();
  301.             }
  302.             $productListForShow $productList;
  303.         }
  304.         $engine $this->container->get("templating");
  305. //        $SD=Supplier::GetSupplierDetailsForMis($em,$supplier_id);
  306.         if ($productList) {
  307.             $Content $engine->render('ApplicationBundle:pages/inventory/report:selected_item_stock.html.twig', array("productList" => $productListForShow'warehouseList' => $warehouseList));
  308.             return new JsonResponse(array("success" => true"content" => $Content'productListForShow' => $productListForShow));
  309.         }
  310.         return new JsonResponse(array("success" => false));
  311.     }
  312.     public function CreateProductAction(Request $request$id 0)
  313.     {
  314.         $ex_id 0;
  315.         $prod_det = [];
  316.         $product_duplicate 0;
  317.         $group_type 1;//item
  318.         $em $this->getDoctrine()->getManager();
  319.         $companyId $this->getLoggedUserCompanyId($request);
  320.         $route $request->get('_route');
  321.         if ($route == 'create_service')
  322.             $group_type 2;//service
  323.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  324.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  325. //                $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  326. //        file_put_contents($path, json_encode(array(
  327. //            'sessionDataString'=>$request->request->get('sessionDataString'),
  328. //            'sessionData'=>json_decode($request->request->get('sessionDataString')),
  329. ////            'invData'=>$data_searched,
  330. //
  331. //        )));//overwrite
  332.         if ($request->isMethod('POST')) {
  333.             if ($id == 0)
  334.                 $id $request->request->has('ex_id') ? $request->request->get('ex_id') : 0;
  335.             if ($id == 0) {
  336.                 if ($group_type == 2)
  337.                     $ext_pr $this->getDoctrine()
  338.                         ->getRepository('ApplicationBundle:AccService')
  339.                         ->findOneBy(
  340.                             array(
  341.                                 'serviceName' => $request->request->get('name'),
  342.                             )
  343.                         );
  344.                 else
  345.                     $ext_pr $this->getDoctrine()
  346.                         ->getRepository('ApplicationBundle:InvProducts')
  347.                         ->findOneBy(
  348.                             array(
  349.                                 'name' => $request->request->get('name'),
  350.                             )
  351.                         );
  352.                 if ($ext_pr)
  353.                     $product_duplicate 1;
  354.             }
  355.             if ($product_duplicate == 1) {
  356.                 $this->addFlash(
  357.                     'error',
  358.                     'Duplicate Entry Found'
  359.                 );
  360.             } else {
  361.                 $image_list = [];
  362.                 $defaultImage "";
  363.                 $defaultImageUploadedFile null;
  364.                 $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
  365. //                if ($request->files->has('product_default_image')) {
  366. //
  367. //
  368. ////                    foreach ($request->files->get('product_default_image') as $uploadedFile)
  369. //                    $defaultImageUploadedFile = $request->files->get('product_default_image');
  370. //                    {
  371. //
  372. //                        $path = "";
  373. //
  374. //                        if ($defaultImageUploadedFile != null) {
  375. //
  376. //                            $fileName = 'p' . md5(uniqid()) . '.' . $defaultImageUploadedFile->guessExtension();
  377. //                            $path = $fileName;
  378. //
  379. //                            if (!file_exists($upl_dir)) {
  380. //                                mkdir($upl_dir, 0777, true);
  381. //                            }
  382. ////                            $file = $uploadedFile->move($upl_dir, $path);
  383. //
  384. //                        }
  385. //                        $file_list[] = $path;
  386. //                        $defaultImage = $path;
  387. //                    }
  388. //
  389. //
  390. //                }
  391. //                if ($request->files->has('product_images')) {
  392. //
  393. //
  394. //                    foreach ($request->files->get('product_default_image') as $ind=>$uploadedFile)
  395. //                    {
  396. //
  397. //                        $path = "";
  398. //
  399. //                        if ($uploadedFile != null) {
  400. //
  401. //                            $fileName = 'p_'.$ind . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  402. //                            $path = $fileName;
  403. //
  404. //                            if (!file_exists($upl_dir)) {
  405. //                                mkdir($upl_dir, 0777, true);
  406. //                            }
  407. ////                            $file = $uploadedFile->move($upl_dir, $path);
  408. //
  409. //                        }
  410. //                        $image_list[] = $path;
  411. //                        if($defaultImage=='' && $ind==0) {
  412. //                            $defaultImage = $path;
  413. //                            $uploadedFile = $path;
  414. //                        }
  415. //
  416. //                    }
  417. //
  418. //
  419. //                }
  420.                 if ($group_type == 2) {
  421.                     $ig $this->getDoctrine()
  422.                         ->getRepository('ApplicationBundle:InvItemGroup')
  423.                         ->findOneBy(
  424.                             array(
  425.                                 'id' => $request->request->get('itemgroupId')
  426.                             )
  427.                         );
  428.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  429.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  430.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  431.                     Inventory::CreateNewService(
  432.                         $this->getDoctrine()->getManager(),
  433.                         $request->request->get('ex_id'),
  434.                         $request->request->get('name'),
  435.                         $companyId,
  436.                         $request->request->get('typeId'),
  437.                         $request->request->get('categoryId'),
  438.                         $request->request->get('brandCompany'),
  439.                         $request->request->get('subCategoryId'),
  440.                         $request->request->get('itemgroupId'),
  441.                         $request->request->get('unitTypeId'),
  442.                         $request->request->get('note'),
  443.                         $request->request->get('alias'''),
  444.                         $request->request->get('categorization_1'''),
  445.                         $request->request->get('categorization_2'''),
  446.                         $request->request->get('categorization_3'''),
  447.                         $request->request->get('categorization_4'''),
  448.                         $request->request->get('purchasePrice'0),
  449.                         $request->request->get('salesPrice'0),
  450.                         $request->request->get('productFdm'''),
  451.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  452.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  453.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  454.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId()
  455.                     );
  456.                     $this->addFlash(
  457.                         'success',
  458.                         'Service Have Been Added/Updated'
  459.                     );
  460.                 } else {
  461.                     $ig $this->getDoctrine()
  462.                         ->getRepository('ApplicationBundle:InvItemGroup')
  463.                         ->findOneBy(
  464.                             array(
  465.                                 'id' => $request->request->get('itemgroupId')
  466.                             )
  467.                         );
  468.                     $defaultPurchaseActionTagId $request->request->get('defaultPurchaseActionTagId''');
  469.                     $ledgerHitAs $request->request->get('ledgerHitAs''');
  470.                     $defaultExpenseId $request->request->get('defaultExpenseId''');
  471.                     $crateData=[];
  472.                     $crateData=[];
  473.                     foreach ($request->request->get('product_crate', []) as $crateIndex=>$crateId)
  474.                     {
  475.                         $crateData[]=array(
  476.                             'id'=>$crateId,
  477.                             'qty'=>$request->request->get('product_qty', []),
  478.                         );
  479.                     }
  480.                     $sizesData=[];
  481.                     foreach ($request->request->get('product_crate', []) as $crateIndex=>$crateId)
  482.                     {
  483.                         $sizesData[]=array(
  484.                             'size'=>$request->request->get('product_size', []),
  485.                             'dimension'=>$request->request->get('product_dimension', []),
  486.                             'dimensionUnitType'=>$request->request->get('product_dimension_unit_type', []),
  487.                             'weight'=>$request->request->get('product_weight', []),
  488.                             'weightUnitType'=>$request->request->get('product_weight_unit_type', []),
  489.                         );
  490.                     }
  491.                     Inventory::CreateNewProduct(
  492.                         $this->getDoctrine()->getManager(),
  493.                         $request->request->get('ex_id'0),
  494.                         $request->request->get('name'''),
  495.                         $request->request->get('model_no'''),
  496.                         $this->getLoggedUserCompanyId($request),
  497.                         $request->request->get('typeId'1),
  498.                         $request->request->get('categoryId'null),
  499.                         $request->request->get('hasSerial'null),
  500.                         $ig->getDraccountsHeadId(),
  501.                         $ig->getCraccountsHeadId(),
  502.                         ($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId $ig->getDefaultPurchaseActionTagId(),
  503.                         $ig->getVatAsExpenseFlag(),
  504.                         $request->request->get('brandCompany'null),
  505.                         $request->request->get('subCategoryId'null),
  506.                         $request->request->get('yearlyDepreciation'0),
  507.                         $request->request->get('purchaseWarrantyMonths'0),
  508.                         $request->request->get('salesWarrantyMonths'0),
  509.                         $request->request->get('startingBalanceUnit'0),
  510.                         $request->request->get('reorderLevel'0),
  511.                         $request->request->get('note'''),
  512.                         $request->request->get('alias'''),
  513.                         $request->request->get('itemgroupId'null),
  514.                         $request->request->get('unitTypeId'null),
  515.                         $request->request->get('hsCode'''),
  516.                         $request->request->get('skuCode'''),
  517.                         $request->files->get('dataSheets'null),
  518.                         $request->request->get('partId'''),
  519.                         $request->request->get('productCode'''),
  520.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  521.                         $request->request->get('purchasePrice'0),
  522.                         $request->request->get('salesPrice'0),
  523.                         $request->files->get('product_default_image'null),
  524.                         $upl_dir,
  525.                         $request->files->get('product_images', []),
  526.                         $request->request->get('expiryDays'0),
  527.                         $request->request->get('dimension'''),
  528.                         $request->request->get('dimensionUnitTypeId'0),
  529.                         $request->request->get('productFdm'''),
  530.                         $request->request->get('weight'''),
  531.                         $request->request->get('weightUnitTypeId'0),
  532.                         $request->request->get('specification'null),
  533.                         $request->request->get('ingredient'null),
  534.                         $request->request->get('nutrition'null),
  535.                         $request->request->get('segregatePriceByColorsFlag'null),
  536.                         $request->request->get('segregatePriceBySizesFlag'null),
  537.                         $request->request->get('categorization_1'''),
  538.                         $request->request->get('categorization_2'''),
  539.                         $request->request->get('categorization_3'''),
  540.                         $request->request->get('categorization_4'''),
  541.                         $request->request->get('weightVarianceValue'0),
  542.                         $request->request->get('weightVarianceType'0),
  543.                         $request->request->get('singleWeight'''),
  544.                         $request->request->get('singleWeightUnitTypeId'0),
  545.                         $request->request->get('singleWeightVarianceValue'0),
  546.                         $request->request->get('singleWeightVarianceType'0),
  547.                         $request->request->get('cartonWeightVarianceValue'0),
  548.                         $request->request->get('cartonWeightVarianceType'0),
  549.                         $request->request->get('cartonCapacityCount'0),
  550.                         $request->request->get('tac'''),
  551.                         $request->request->get('sellable'0),
  552.                         $request->request->get('abstract'0),
  553.                         $request->request->get('tags'''),
  554.                         $request->request->get('markerFlags'''),
  555.                         $request->request->get('defaultColorId'0),
  556.                         $request->request->get('product_color', []),
  557.                         $request->request->get('product_size', []),
  558.                         ($ledgerHitAs != '') ? $ledgerHitAs $ig->getLedgerHitAs(),
  559.                         ($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId $ig->getDefaultExpenseId(),
  560.                         $crateData,
  561.                         $sizesData
  562.                     );
  563.                     $this->addFlash(
  564.                         'success',
  565.                         'Product Have Been Added/Updated'
  566.                     );
  567.                 }
  568.             }
  569.             if ($request->request->has('returnJson')) {
  570.                 return new JsonResponse(array(
  571.                     'success' => true
  572.                 ));
  573.             }
  574.             if ($group_type == 2)
  575.                 return $this->redirectToRoute("create_service");
  576.             else
  577.                 return $this->redirectToRoute("create_product");
  578.         }
  579.         if ($id != 0) {
  580.             $ex_id $id;
  581.             if ($group_type == 2)
  582.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:AccService')->findOneBy(array(
  583.                     'serviceId' => $id//for now for stock of goods
  584. //                    'opening_locked'=>0
  585.                 ));
  586.             else
  587.                 $prod_det $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  588.                     'id' => $id//for now for stock of goods
  589. //                    'opening_locked'=>0
  590.                 ));
  591.         }
  592.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  593.             'name' => 'warehouse_action_1'//for now for stock of goods
  594.         ));
  595.         return $this->render('ApplicationBundle:pages/inventory/input_forms:create_product.html.twig',
  596.             array(
  597.                 'page_title' => $group_type == 'Service Entry' 'Product Entry',
  598.                 'group_type' => $group_type,
  599.                 'inv_head' => $inv_head $inv_head->getData() : '',
  600. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  601.                 'services' => Inventory::ServiceList($this->getDoctrine()->getManager()),
  602.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  603.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  604.                 'itemgroup' => Inventory::ItemGroupList($em$companyId$group_type),
  605.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  606.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  607.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager(), 1),
  608.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  609.                 'ex_id' => $ex_id,
  610.                 'warehouse_action_list' => $warehouse_action_list,
  611.                 'warehouse_action_list_array' => $warehouse_action_list_array,
  612.                 'markerFlags' => InventoryConstant::$SPECIAL_MARKER_ARRAY,
  613.                 'ex_prod_det' => $prod_det
  614.             )
  615.         );
  616.     }
  617.     public function ProductListAction(Request $request)
  618.     {
  619.         $em $this->getDoctrine()->getManager();
  620.         $companyId $this->getLoggedUserCompanyId($request);
  621.         $listData Inventory::GetProductListForProductListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  622.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  623.             if ($request->query->has('dataTableQry')) {
  624.                 return new JsonResponse(
  625.                     $listData
  626.                 );
  627.             }
  628.         }
  629.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  630.             'name' => 'warehouse_action_1'//for now for stock of goods
  631.         ));
  632.         return $this->render('ApplicationBundle:pages/inventory/view:product_list.html.twig',
  633.             array(
  634.                 'page_title' => 'Product List',
  635.                 'inv_head' => $inv_head $inv_head->getData() : '',
  636. //                'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  637.                 'products' => [],
  638.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  639.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  640.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  641.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  642.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  643. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  644.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  645.             )
  646.         );
  647.     }
  648.     public function SalesVsDeliveryListAction(Request $request)
  649.     {
  650.         $em $this->getDoctrine()->getManager();
  651.         $session $request->getSession();
  652.         $userType $session->get(UserConstants::USER_TYPE);
  653.         $userId $session->get(UserConstants::USER_ID);
  654.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  655.             'approved' => GeneralConstant::APPROVED,
  656. //            'stage' => GeneralConstant::STAGE_PENDING
  657.         );
  658.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  659.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  660.         }
  661. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  662. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  663. //            $selectiveDocumentsFlag=1; //by default will show only selective
  664. //            if(isset($userRestrictions['canSeeAllSo'])) {
  665. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  666. //                    $selectiveDocumentsFlag = 0;
  667. //                }
  668. //            }
  669. //
  670. //            if($selectiveDocumentsFlag==1)
  671. //            {
  672. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  673. //            }
  674. //        }
  675.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  676.             'name' => 'warehouse_action_1'//for now for stock of goods
  677.         ));
  678.         if ($request->query->has('queryDate')) {
  679.             $date = new \DateTime($request->query->get('queryDate'));
  680.         } else {
  681.             $today = new \DateTime();
  682.             $todayStr $today->format('Y-m-d');
  683.             $date = new \DateTime($todayStr);
  684.         }
  685.         $orderQryArray['salesOrderDate'] = $date;
  686.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  687.         $so_ids = [];
  688.         $so_data = [];
  689.         $so_item_ids = [];
  690.         $so_item_data = [];
  691.         foreach ($salesOrders as $salesOrder) {
  692.             if ($salesOrder->getSalesOrderDate() > $date)
  693.                 continue;
  694.             $so_ids[] = $salesOrder->getSalesOrderId();
  695.             $so_data[$salesOrder->getSalesOrderId()] = array(
  696.                 "id" => $salesOrder->getSalesOrderId(),
  697.                 "documentHash" => $salesOrder->getDocumentHash(),
  698.                 "clientId" => $salesOrder->getClientId(),
  699.             );
  700.         }
  701.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  702.             'salesOrderId' => $so_ids,
  703.         ));
  704.         foreach ($salesOrderItems as $salesOrderItem) {
  705.             $so_item_ids[] = $salesOrderItem->getId();
  706.             $so_item_data[$salesOrderItem->getId()] = array(
  707.                 "id" => $salesOrderItem->getId(),
  708.                 "productId" => $salesOrderItem->getProductId(),
  709.                 "productName" => $salesOrderItem->getProductNameFdm(),
  710.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  711.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  712.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  713. //                "documentHash"=>$salesOrder->getDocumentHash(),
  714.                 "qty" => $salesOrderItem->getQty(),
  715.                 "transitQty" => $salesOrderItem->getTransitQty(),
  716.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  717.             );
  718.         }
  719.         return $this->render('ApplicationBundle:pages/inventory/view:sales_vs_delivery_status.html.twig',
  720.             array(
  721.                 'page_title' => 'Order Vs. Disperse',
  722.                 'inv_head' => $inv_head $inv_head->getData() : '',
  723.                 'so_data' => $so_data,
  724.                 'queryDate' => $date,
  725.                 'so_item_data' => $so_item_data,
  726.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  727.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  728.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  729.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  730.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  731.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  732.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  733. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  734.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  735.             )
  736.         );
  737.     }
  738.     public function DeliveryPendingOrderListAction(Request $request)
  739.     {
  740.         $em $this->getDoctrine()->getManager();
  741.         $session $request->getSession();
  742.         $userType $session->get(UserConstants::USER_TYPE);
  743.         $userId $session->get(UserConstants::USER_ID);
  744.         $orderQryArray = array('status' => GeneralConstant::ACTIVE,
  745.             'approved' => GeneralConstant::APPROVED,
  746.             'stage' => GeneralConstant::STAGE_PENDING
  747.         );
  748.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  749.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  750.         }
  751. //        if($userType==UserConstants::USER_TYPE_GENERAL){
  752. //            $userRestrictions= Users::getUserApplicationAccessSettings($em,$userId )['options'];
  753. //            $selectiveDocumentsFlag=1; //by default will show only selective
  754. //            if(isset($userRestrictions['canSeeAllSo'])) {
  755. //                if ($userRestrictions['canSeeAllSo'] == 1) {
  756. //                    $selectiveDocumentsFlag = 0;
  757. //                }
  758. //            }
  759. //
  760. //            if($selectiveDocumentsFlag==1)
  761. //            {
  762. //                $allowedLoginIds=MiscActions::getLoginIdsByUserId($em,$session->get(UserConstants::USER_ID));
  763. //            }
  764. //        }
  765.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  766.             'name' => 'warehouse_action_1'//for now for stock of goods
  767.         ));
  768.         if ($request->query->has('queryDate')) {
  769.             $date = new \DateTime($request->query->get('queryDate'));
  770.         } else {
  771.             $today = new \DateTime();
  772.             $todayStr $today->format('Y-m-d');
  773.             $date = new \DateTime($todayStr);
  774.         }
  775. //        $orderQryArray['salesOrderDate'] = $date;
  776.         $salesOrders $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
  777.         $so_ids = [];
  778.         $so_data = [];
  779.         $so_item_ids = [];
  780.         $so_item_data = [];
  781.         foreach ($salesOrders as $salesOrder) {
  782.             if ($salesOrder->getSalesOrderDate() > $date)
  783.                 continue;
  784.             $so_ids[] = $salesOrder->getSalesOrderId();
  785.             $so_data[$salesOrder->getSalesOrderId()] = array(
  786.                 "id" => $salesOrder->getSalesOrderId(),
  787.                 "documentHash" => $salesOrder->getDocumentHash(),
  788.                 "clientId" => $salesOrder->getClientId(),
  789.             );
  790.         }
  791.         $salesOrderItems $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
  792.             'salesOrderId' => $so_ids,
  793.         ));
  794.         foreach ($salesOrderItems as $salesOrderItem) {
  795.             $so_item_ids[] = $salesOrderItem->getId();
  796.             $so_item_data[$salesOrderItem->getId()] = array(
  797.                 "id" => $salesOrderItem->getId(),
  798.                 "productId" => $salesOrderItem->getProductId(),
  799.                 "productName" => $salesOrderItem->getProductNameFdm(),
  800.                 "salesOrderId" => $salesOrderItem->getSalesOrderId(),
  801.                 "clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
  802.                 "soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
  803. //                "documentHash"=>$salesOrder->getDocumentHash(),
  804.                 "qty" => $salesOrderItem->getQty(),
  805.                 "transitQty" => $salesOrderItem->getTransitQty(),
  806.                 "deliveredQty" => $salesOrderItem->getDelivered(),
  807.             );
  808.         }
  809.         return $this->render('ApplicationBundle:pages/inventory/view:delivery_pending_order_list.html.twig',
  810.             array(
  811.                 'page_title' => 'Pending Delivery',
  812.                 'inv_head' => $inv_head $inv_head->getData() : '',
  813.                 'so_data' => $so_data,
  814.                 'queryDate' => $date,
  815.                 'so_item_data' => $so_item_data,
  816.                 'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  817.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  818.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  819.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  820.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  821.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  822.                 'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  823. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  824.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  825.             )
  826.         );
  827.     }
  828.     public function ItemGroupAction(Request $request$id 0)
  829.     {
  830.         $ex_id 0;
  831.         $det = [];
  832.         $em $this->getDoctrine()->getManager();
  833.         $companyId $this->getLoggedUserCompanyId($request);
  834.         $group_type 1;//item
  835.         $route $request->get('_route');
  836.         if ($route == 'service_group')
  837.             $group_type 2;//service
  838.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  839.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  840.         if ($request->isMethod('POST')) {
  841.             Inventory::CreateItemGroup($this->getDoctrine()->getManager(),
  842.                 $request->request->get('ex_id'),
  843.                 $this->getLoggedUserCompanyId($request),
  844.                 $request->request,
  845.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  846.         }
  847.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  848.             'name' => 'warehouse_action_1'//for now for stock of goods
  849.         ));
  850.         if ($id != 0) {
  851.             $ex_id $id;
  852.             $det $this->getDoctrine()->getRepository('ApplicationBundle:InvItemGroup')->findOneBy(array(
  853.                 'id' => $id//for now for stock of goods
  854. //                    'opening_locked'=>0
  855.             ));
  856.         }
  857.         return $this->render('ApplicationBundle:pages/inventory/input_forms:item_group.html.twig',
  858.             array(
  859.                 'page_title' => $group_type == "Item Groups" "Service Groups",
  860.                 'inv_head' => $inv_head $inv_head->getData() : '',
  861.                 'group_type' => $group_type,
  862.                 'igList' => Inventory::ItemGroupList($em$companyId$group_type),
  863.                 'warehouse_action_list' => $warehouse_action_list,
  864. //                'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
  865.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  866.                 'ex_id' => $ex_id,
  867.                 'ex_det' => $det
  868.             )
  869.         );
  870.     }
  871.     public function addStartingOpeningInOutAction(Request $request$refreshed_opening 0)
  872.     {
  873.         //be very careful!!
  874.         $em $this->getDoctrine()->getManager();
  875. //        $last_refresh_date="";
  876.         //steps
  877.         //1. set all inventory to their opening position
  878.         $assign_list = array();
  879.         $data = array();
  880.         if ($refreshed_opening == 0) {
  881.             $new_cc $em
  882.                 ->getRepository('ApplicationBundle:AccSettings')
  883.                 ->findOneBy(
  884.                     array(
  885.                         'name' => 'accounting_year_start',
  886.                     )
  887.                 );
  888.             $date_start = new \DateTime($new_cc->getData());
  889.             $date_start_str $date_start->format('Y-m-d');
  890.             $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  891. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  892.             $stmt $em->getConnection()->prepare($closingQuery);
  893.             $stmt->execute();
  894.             $iniClosing $stmt->fetchAll();
  895. //                $stmt = $em->getConnection()->prepare($transQuery);
  896. //                $stmt->execute();
  897. //                $iniTrans = $stmt->fetchAll();
  898.             $singleClosing_byProductId = array();
  899.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  900.             foreach ($iniClosing as $item) {
  901.                 if (!isset($singleClosing_byProductId[$item['product_id']])) {
  902.                     $singleClosing_byProductId[$item['product_id']] = array(
  903.                         'date' => $item['date'],
  904.                         'qtyAdd' => $item['qty_addition'],
  905.                         'qtySub' => '0',
  906.                         'valueAdd' => $item['addition'],
  907.                         'valueSub' => '0',
  908.                         'fromWarehouse' => 0,
  909.                         'toWarehouse' => $item['warehouse_id'],
  910.                         'fromWarehouseSub' => 0,
  911.                         'toWarehouseSub' => $item['action_tag_id'],
  912.                         'price' => ($item['addition'] / $item['qty_addition'])
  913.                     );
  914.                 }
  915.             }
  916.             //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  917. //                foreach ($iniTrans as $item) {
  918. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  919. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  920. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  921. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  922. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  923. //                    }
  924. //                }
  925.             foreach ($singleClosing_byProductId as $key => $item) {
  926.                 if (!isset($data[$key])) {
  927.                     $data[$key][] = $item;
  928.                 }
  929.             }
  930.             //now that we go the data we can empty the closing table
  931. //                $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  932. //    truncate `inv_closing_balance`;
  933. //    truncate `inventory_storage`;
  934. //    truncate `inv_item_transaction`;';
  935. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  936. //                $stmt->execute();
  937. //                $stmt->closeCursor();
  938. //                $stmt->fetchAll();
  939.             $total_inv_value_in 0;
  940.             foreach ($data as $key => $item) {
  941.                 if (!empty($item)) {
  942.                     foreach ($item as $entry) {
  943.                         $transDate = new \DateTime($entry['date']);
  944.                         $new = new InvItemInOut();
  945.                         $new->setProductId($key);
  946.                         $new->setWarehouseId($entry['toWarehouse']);
  947.                         $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  948.                         $new->setActionTagId($entry['toWarehouseSub']);
  949.                         $new->setTransactionDate($transDate);
  950.                         $new->setQty($entry['qtyAdd']);
  951.                         $new->setPrice($entry['price']);
  952.                         $new->setAmount($entry['qtyAdd'] * $entry['price']);
  953.                         $new->setEntity(0);// opening =0
  954.                         $new->setEntityId(0);// opening =0
  955.                         $new->setDebitCreditHeadId(0);// opening =0
  956.                         $new->setVoucherIds(null);// opening =0
  957.                         $em->persist($new);
  958.                         $em->flush();
  959.                         $total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
  960.                     }
  961.                 }
  962.             }
  963.             $refreshed_opening 1;
  964. //                $terminate=1;
  965. //                $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
  966.             return new JsonResponse(array(
  967.                 "success" => true,
  968.             ));
  969.             //now call the function which will add the 1st ever entry or opening entry
  970.         }
  971.         //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  972.         return new JsonResponse(array(
  973.             "success" => false,
  974.         ));
  975.     }
  976.     public function RefreshInventoryAction(Request $request$refreshed_opening 0)
  977.     {
  978.         //be very careful!!
  979.         $em $this->getDoctrine()->getManager();
  980.         $refreshed_opening 0;
  981.         $last_refresh_date "";
  982.         $last_refresh_date_obj "";
  983.         $terminate 0;
  984.         $companyId $this->getLoggedUserCompanyId($request);
  985.         $modifyAccTransaction $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
  986.         $modifyProductionPrice $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
  987. //        $last_refresh_date="";
  988.         if ($request->isMethod('POST')) {
  989.             //steps
  990.             //1. set all inventory to their opening position
  991.             $assign_list = array();
  992.             $data = array();
  993.             if ($request->request->has('inventory_refreshed'))
  994.                 $refreshed_opening $request->request->get('inventory_refreshed');
  995.             if ($request->request->has('last_refresh_date'))
  996.                 $last_refresh_date $request->request->get('last_refresh_date');
  997.             if ($refreshed_opening == 0) {
  998. //                System::log_it($this->container->getParameter('kernel.root_dir'), "",
  999. //                    'inventory_refresh_debug', 0); //last er 1 is append
  1000.                 $new_cc $em
  1001.                     ->getRepository('ApplicationBundle:AccSettings')
  1002.                     ->findOneBy(
  1003.                         array(
  1004.                             'name' => 'accounting_year_start',
  1005.                         )
  1006.                     );
  1007.                 $date_start = new \DateTime($new_cc->getData());
  1008.                 $date_start_str $date_start->format('Y-m-d');
  1009.                 $closingQuery "SELECT * from  inv_closing_balance where `date` <='" $date_start_str " 00:00:00' and opening=0  order by product_id desc, `date` asc ";
  1010. //                $transQuery = "SELECT * from  inv_item_transaction  where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
  1011.                 $stmt $em->getConnection()->prepare($closingQuery);
  1012.                 $stmt->execute();
  1013.                 $iniClosing $stmt->fetchAll();
  1014. //                $stmt = $em->getConnection()->prepare($transQuery);
  1015. //                $stmt->execute();
  1016. //                $iniTrans = $stmt->fetchAll();
  1017.                 $singleClosing_byProductId = array();
  1018.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1019.                 foreach ($iniClosing as $item) {
  1020.                     if (!isset($singleClosing_byProductId[$item['product_id']])) {
  1021.                         $singleClosing_byProductId[$item['product_id']] = array(
  1022.                             'date' => $item['date'],
  1023.                             'qtyAdd' => $item['qty_addition'],
  1024.                             'qtySub' => '0',
  1025.                             'valueAdd' => $item['addition'],
  1026.                             'valueSub' => '0',
  1027.                             'fromWarehouse' => 0,
  1028.                             'toWarehouse' => $item['warehouse_id'],
  1029.                             'fromWarehouseSub' => 0,
  1030.                             'toWarehouseSub' => $item['action_tag_id'],
  1031.                             'price' => $item['qty_addition'] != ? ($item['addition'] / $item['qty_addition']) : $item['addition']
  1032.                         );
  1033.                     }
  1034.                 }
  1035.                 //now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
  1036. //                foreach ($iniTrans as $item) {
  1037. //                    if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
  1038. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
  1039. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
  1040. //                        $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
  1041. //                        $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
  1042. //                    }
  1043. //                }
  1044.                 foreach ($singleClosing_byProductId as $key => $item) {
  1045.                     if (!isset($data[$key])) {
  1046.                         $data[$key][] = $item;
  1047.                     }
  1048.                 }
  1049.                 //new one
  1050.                 //chekc if ultra opening stock received note exists if not create it
  1051.                 $mo $em
  1052.                     ->getRepository('ApplicationBundle:StockReceivedNote')
  1053.                     ->findOneBy(
  1054.                         array(
  1055.                             'documentHash' => '_MASTER_OPENING_',
  1056.                             'typeHash' => 'SR',
  1057.                             'prefixHash' => 4,
  1058.                             'assocHash' => '_MASTER_OPENING_',
  1059.                             'numberHash' => 1,
  1060.                         )
  1061.                     );
  1062.                 if (!$mo) {
  1063.                     //doensot exist to add :)
  1064. //                    $products = $post_data->get('products');
  1065. //                    $qty = $post_data->get('qty');
  1066. //                    $note = $post_data->get('note');
  1067.                     $new = new StockReceivedNote();
  1068.                     $new->setStockReceivedNoteDate(new \DateTime($date_start_str));
  1069.                     $new->setCompanyId($companyId);
  1070.                     $new->setDocumentHash('_MASTER_OPENING_');
  1071.                     $new->setTypeHash('SR');
  1072.                     $new->setPrefixHash(4);
  1073.                     $new->setAssocHash('_MASTER_OPENING_');
  1074.                     $new->setNumberHash(1);
  1075.                     $new->setCreditHeadId(0);
  1076.                     $new->setStockTransferId(0);
  1077.                     $new->setSalesOrderId(0);
  1078.                     $new->setType(4);
  1079.                     $new->setStatus(GeneralConstant::ACTIVE);
  1080.                     $new->setWarehouseId(0);
  1081.                     $new->setNote('');
  1082.                     $new->setAutoCreated(1);
  1083.                     $new->setApproved(GeneralConstant::APPROVED);
  1084. //        $new->setIndentTagged(0);
  1085.                     $new->setStage(GeneralConstant::STAGE_COMPLETE);
  1086.                     $new->setCreatedLoginId(0);
  1087.                     $new->setEditedLoginId(0);
  1088.                     $em->persist($new);
  1089.                     $em->flush();
  1090.                     $SRID $new->getStockReceivedNoteId();
  1091.                     $last_refresh_date_obj $new->getStockReceivedNoteDate();
  1092.                     //now add items to details
  1093.                     foreach ($data as $key => $item) {
  1094.                         if (!empty($item)) {
  1095.                             foreach ($item as $entry) {
  1096.                                 $transDate = new \DateTime($entry['date']);
  1097.                                 if ($last_refresh_date_obj == '') {
  1098.                                     $last_refresh_date_obj $transDate;
  1099.                                 } else if ($transDate $last_refresh_date_obj) {
  1100.                                     $last_refresh_date_obj $transDate;
  1101.                                 }
  1102.                                 $new = new StockReceivedNoteItem();
  1103.                                 $new->setStockReceivedNoteId($SRID);
  1104.                                 $new->setStockTransferItemId(0);
  1105.                                 $salesCodeRange = [];
  1106.                                 $salesCodeRangeStr '';
  1107.                                 $new->setSalesCodeRange("[" $salesCodeRangeStr "]");
  1108.                                 $new->setQty($entry['qtyAdd']);
  1109.                                 $new->setPrice($entry['price']);
  1110.                                 $new->setBalance($entry['qtyAdd']);
  1111.                                 $new->setProductId($key);
  1112.                                 $new->setWarrantyMon(0);
  1113.                                 $new->setWarehouseId($entry['toWarehouse']);
  1114.                                 $new->setWarehouseActionId($entry['toWarehouseSub']);
  1115.                                 $em->persist($new);
  1116.                                 $em->flush();
  1117.                             }
  1118.                         }
  1119.                     }
  1120. //                    for ($i = 0; $i < count($products); $i++) {
  1121. //
  1122. //
  1123. //                        $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
  1124. //                    }
  1125.                 }
  1126.                 if ($mo)
  1127.                     $last_refresh_date_obj $mo->getStockReceivedNoteDate();
  1128.                 $last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
  1129.                 //new ends
  1130.                 //now that we go the data we can empty the closing table
  1131.                 $get_kids_sql "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
  1132. UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
  1133.     truncate `inv_closing_balance`;
  1134.     truncate `inventory_storage`;
  1135.     truncate `inv_item_transaction`;";
  1136.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  1137.                 $stmt->execute();
  1138.                 $stmt->closeCursor();
  1139. //                $stmt->fetchAll();
  1140. //                foreach ($data as $key => $item) {
  1141. //                    if (!empty($item)) {
  1142. //                        foreach ($item as $entry) {
  1143. //                            $transDate = new \DateTime($entry['date']);
  1144. //                            Inventory::addItemToInventoryCompact($em,
  1145. //                                $key,
  1146. //                                $entry['fromWarehouse'],
  1147. //                                $entry['toWarehouse'],
  1148. //                                $entry['fromWarehouseSub'],
  1149. //                                $entry['toWarehouseSub'],
  1150. //                                $transDate,
  1151. //                                $entry['qtyAdd'],
  1152. //                                $entry['qtySub'],
  1153. //                                $entry['valueAdd'],
  1154. //                                $entry['valueSub'],
  1155. //                                $entry['price'],
  1156. //                                $this->getLoggedUserCompanyId($request));
  1157. //                            if ($last_refresh_date_obj == '') {
  1158. //                                $last_refresh_date_obj = $transDate;
  1159. //                            } else if ($transDate < $last_refresh_date_obj) {
  1160. //                                $last_refresh_date_obj = $transDate;
  1161. //                            }
  1162. //                        }
  1163. //                    }
  1164. //                }
  1165.                 $refreshed_opening 1;
  1166. //                $terminate=1;
  1167.                 if ($last_refresh_date_obj == "") {
  1168.                     $last_refresh_date $date_start_str;
  1169.                 } else {
  1170.                     $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1171.                 }
  1172.                 return new JsonResponse(array(
  1173.                     "success" => true,
  1174.                     "last_refresh_date" => $last_refresh_date,
  1175.                     "inventory_refreshed" => $refreshed_opening
  1176.                 ));
  1177.                 //now call the function which will add the 1st ever entry or opening entry
  1178.             }
  1179.             //now if opening was refreshed before then we can get the next date provided that no transaction on start date
  1180.             if ($last_refresh_date != '')
  1181.                 $last_refresh_date_obj = new \DateTime($last_refresh_date);
  1182.             else {
  1183.                 $new_cc $em
  1184.                     ->getRepository('ApplicationBundle:AccSettings')
  1185.                     ->findOneBy(
  1186.                         array(
  1187.                             'name' => 'accounting_year_start',
  1188.                         )
  1189.                     );
  1190.                 $last_refresh_date_obj = new \DateTime($new_cc->getData());
  1191.                 $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1192.             }
  1193.             $last_refresh_date_obj->modify('+1 day');
  1194.             $today = new \DateTime();
  1195.             if ($last_refresh_date_obj $today) {
  1196.                 $terminate 1;
  1197.             }
  1198.             $last_refresh_date $last_refresh_date_obj->format('Y-m-d');
  1199.             //ok now we got the date so get grn item on this date
  1200.             //GRN
  1201.             $query "SELECT grn_item.*, grn.grn_date, grn.document_hash from  grn_item
  1202.               join grn on grn.grn_id=grn_item.grn_id
  1203.             where grn.grn_date ='" $last_refresh_date " 00:00:00' and grn.approved=1";
  1204.             $stmt $em->getConnection()->prepare($query);
  1205.             $stmt->execute();
  1206.             $queryData $stmt->fetchAll();
  1207.             $grn_ids = [];
  1208.             foreach ($queryData as $item) {
  1209.                 $data[$item['product_id']][] = array(
  1210.                     'date' => $last_refresh_date,
  1211.                     'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
  1212.                     'entityId' => $item['grn_id'],
  1213.                     'colorId' => $item['color_id'],
  1214.                     'sizeId' => $item['size_id'],
  1215.                     'entityDocHash' => $item['document_hash'],
  1216.                     'qtyAdd' => $item['qty'],
  1217.                     'qtySub' => 0,
  1218.                     'valueAdd' => ($item['qty'] * $item['price_with_expense']),
  1219.                     'valueSub' => 0,
  1220.                     'price' => $item['price_with_expense'],
  1221.                     'fromWarehouse' => 0,
  1222.                     'toWarehouse' => $item['warehouse_id'],
  1223.                     'fromWarehouseSub' => 0,
  1224. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1225.                     'toWarehouseSub' => $item['warehouse_action_id']
  1226.                 );
  1227.                 if (!in_array($item['grn_id'], $grn_ids))
  1228.                     $grn_ids[] = $item['grn_id'];
  1229.             }
  1230.             //now add grns
  1231.             foreach ($data as $key => $item) {
  1232.                 if (!empty($item)) {
  1233.                     foreach ($item as $entry) {
  1234.                         $transDate = new \DateTime($entry['date']);
  1235.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1236.                             $key,
  1237.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1238.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1239.                             $entry['fromWarehouse'],
  1240.                             $entry['toWarehouse'],
  1241.                             $entry['fromWarehouseSub'],
  1242.                             $entry['toWarehouseSub'],
  1243.                             $transDate,
  1244.                             $entry['qtyAdd'],
  1245.                             $entry['qtySub'],
  1246.                             $entry['valueAdd'],
  1247.                             $entry['valueSub'],
  1248.                             $entry['price'],
  1249.                             $this->getLoggedUserCompanyId($request),
  1250.                             0,
  1251.                             $entry['entity'],
  1252.                             $entry['entityId'],
  1253.                             $entry['entityDocHash'],
  1254.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
  1255.                         );
  1256.                         if ($last_refresh_date_obj == '') {
  1257.                             $last_refresh_date_obj $transDate;
  1258.                         } else if ($transDate $last_refresh_date_obj) {
  1259.                             $last_refresh_date_obj $transDate;
  1260.                         }
  1261.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1262.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1263.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1264.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1265.                             "",
  1266.                             'inventory_refresh_debug'1); //last er 1 is append
  1267.                     }
  1268.                 }
  1269.             }
  1270.             ///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
  1271. //            $grn=$em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1272. //                'grnId'=>$grn_ids,
  1273. //                'modifyVoucherFlag'=>1 //have to add this flag
  1274. //            ));
  1275.             foreach ($grn_ids as $grn_id) {
  1276.                 if ($modifyAccTransaction == 1)
  1277.                     Inventory::ModifyGrnTransactions($em$grn_id1);
  1278.                 else
  1279.                     Inventory::ModifyGrnTransactions($em$grn_id);
  1280.             }
  1281.             //adding voucher ends
  1282.             $inv_head_list_by_wa = [];
  1283.             $inv_head_list = [];
  1284.             $cogs_head 0;
  1285.             $cogs_head 0;
  1286.             $internal_proj 0;
  1287. //            if ($project) {
  1288. //                if ($project->getProjectType() == 2) {
  1289. //                    $cogs_head = $project->getInternalProjectAssetHeadId();
  1290. //                    $internal_proj = 1;
  1291. //                } else {
  1292. //                    $cogs_head_qry = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1293. //                        'name' => 'cogs'
  1294. //                    ));
  1295. //                    $cogs_head = $cogs_head_qry->getData();
  1296. //                }
  1297. //            } else {
  1298.             $cogs_head_qry $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1299.                 'name' => 'cogs'
  1300.             ));
  1301.             $cogs_head $cogs_head_qry->getData();
  1302. //            }
  1303.             $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');
  1304.             foreach ($warehouse_action_list as $wa) {
  1305.                 $inv_head_data $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1306.                         'name' => 'warehouse_action_' $wa['id'])
  1307.                 );
  1308.                 if ($inv_head_data) {
  1309.                     $inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
  1310.                     $inv_head_list[] = $inv_head_data->getData();
  1311.                 }
  1312.             }
  1313.             $data = [];
  1314.             //____________STOCK_RECEIVED___________________
  1315.             $docEntity "StockReceivedNote";
  1316.             $docEntityIdField "stockReceivedNoteId";
  1317.             $accTransactionDataByDocId = [];
  1318.             $query "SELECT stock_received_note_item.*, stock_received_note.stock_received_note_date, stock_received_note.type, stock_received_note.document_hash from  stock_received_note_item
  1319.               join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
  1320.             where stock_received_note.stock_received_note_date ='" $last_refresh_date " 00:00:00' and stock_received_note.approved=1";
  1321.             $stmt $em->getConnection()->prepare($query);
  1322.             $stmt->execute();
  1323.             $queryData $stmt->fetchAll();
  1324.             $grn_ids = [];
  1325.             foreach ($queryData as $item) {
  1326.                 $data[$item['product_id']][] = array(
  1327.                     'date' => $last_refresh_date,
  1328.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  1329.                     'entityId' => $item['stock_received_note_id'],
  1330.                     'colorId' => $item['color_id'],
  1331.                     'sizeId' => $item['size_id'],
  1332.                     'type' => $item['type'],
  1333.                     'entityDocHash' => $item['document_hash'],
  1334.                     'qtyAdd' => $item['qty'],
  1335.                     'qtySub' => 0,
  1336.                     'valueAdd' => ($item['qty'] * $item['price']),
  1337.                     'valueSub' => 0,
  1338.                     'price' => $item['price'],
  1339.                     'fromWarehouse' => 0,
  1340.                     'toWarehouse' => $item['warehouse_id'],
  1341.                     'fromWarehouseSub' => 0,
  1342. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1343.                     'toWarehouseSub' => $item['warehouse_action_id']
  1344.                 );
  1345. //                if (!in_array($item['grn_id'], $grn_ids))
  1346. //                    $grn_ids[] = $item['grn_id'];
  1347.             }
  1348.             foreach ($data as $key => $item) {
  1349.                 if (!empty($item)) {
  1350.                     foreach ($item as $entry) {
  1351.                         $transDate = new \DateTime($entry['date']);
  1352.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1353.                             $key,
  1354.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1355.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1356.                             $entry['fromWarehouse'],
  1357.                             $entry['toWarehouse'],
  1358.                             $entry['fromWarehouseSub'],
  1359.                             $entry['toWarehouseSub'],
  1360.                             $transDate,
  1361.                             $entry['qtyAdd'],
  1362.                             $entry['qtySub'],
  1363.                             $entry['valueAdd'],
  1364.                             $entry['valueSub'],
  1365.                             $entry['price'],
  1366.                             $this->getLoggedUserCompanyId($request),
  1367.                             0,
  1368.                             $entry['entity'],
  1369.                             $entry['entityId'],
  1370.                             $entry['entityDocHash'],
  1371.                             $entry['type'] == ?
  1372.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
  1373.                                 ($entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
  1374.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
  1375.                         );
  1376.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1377.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1378.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1379.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1380.                             "",
  1381.                             'inventory_refresh_debug'1); //last er 1 is append
  1382.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1383.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1384.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1385.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  1386.                         else
  1387.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  1388.                         if ($last_refresh_date_obj == '') {
  1389.                             $last_refresh_date_obj $transDate;
  1390.                         } else if ($transDate $last_refresh_date_obj) {
  1391.                             $last_refresh_date_obj $transDate;
  1392.                         }
  1393.                     }
  1394.                 }
  1395.             }
  1396.             if ($modifyAccTransaction == 1) {
  1397.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1398.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1399.                         $docEntityIdField => $docId,
  1400.                     ));;
  1401.                     if ($docHere) {
  1402.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1403.                         if ($curr_v_ids == null)
  1404.                             $curr_v_ids = [];
  1405.                         $skipVids = [];
  1406.                         $toChangeVid 0;
  1407.                         $voucher null;
  1408.                         foreach ($curr_v_ids as $vid) {
  1409.                             if (in_array($vid$skipVids))
  1410.                                 continue;
  1411.                             $skipVids[] = $vid//to prevent duplicate query
  1412.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1413.                                 'transactionId' => $vid,
  1414.                             ));;
  1415.                             if ($voucher) {
  1416.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1417.                                     $toChangeVid $vid;
  1418.                                 } else {
  1419.                                     continue;
  1420.                                 }
  1421.                             }
  1422.                         }
  1423.                         if ($toChangeVid == 0) {
  1424.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1425.                                 $em,
  1426.                                 $docHere->getStockReceivedNoteDate()->format('Y-m-d'),
  1427.                                 0,
  1428.                                 AccountsConstant::VOUCHER_JOURNAL,
  1429.                                 'Journal For Stock Received Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1430.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1431.                                 'JV',
  1432.                                 'GN',
  1433.                                 0,
  1434.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1435.                                 0,
  1436.                                 $docHere->getCreatedLoginId(),
  1437.                                 $docHere->getCompanyId(),
  1438.                                 '',
  1439.                                 0,
  1440.                                 1
  1441.                             );
  1442.                             $em->flush();
  1443.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1444.                                 'transactionId' => $toChangeVid,
  1445.                             ));;
  1446.                         }
  1447.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1448.                         $tot_inv_amount 0;
  1449.                         foreach ($transData as $k => $v) {
  1450.                             $tot_inv_amount += ($v);
  1451.                             Accounts::CreateNewTransactionDetails($em,
  1452.                                 '',
  1453.                                 $toChangeVid,
  1454.                                 Generic::CurrToInt($v),
  1455.                                 $k,
  1456.                                 'Inventory Inward For - ' $docHere->getDocumentHash(),
  1457.                                 AccountsConstant::DEBIT,
  1458.                                 0,
  1459.                                 [],
  1460.                                 [],
  1461.                                 $docHere->getCreatedLoginId()
  1462.                             );
  1463.                         }
  1464.                         $stockReceivedType $docHere->getType();
  1465.                         $to_balance_head 0;
  1466.                         if (in_array($stockReceivedType, [23]))
  1467.                             $to_balance_head $docHere->getCreditHeadId();
  1468.                         else {
  1469.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1470.                                     'name' => 'inv_on_transit_head')
  1471.                             );
  1472.                             if ($inv_transit_head)
  1473.                                 $to_balance_head $inv_transit_head->getData();
  1474.                         }
  1475.                         Accounts::CreateNewTransactionDetails($em,
  1476.                             '',
  1477.                             $toChangeVid,
  1478.                             Generic::CurrToInt($tot_inv_amount),
  1479.                             $to_balance_head,
  1480.                             in_array($stockReceivedType, [23]) ? 'Balancing of Stock in Items for -' $docHere->getDocumentHash() : 'In Transit Items for -' $docHere->getDocumentHash(),
  1481.                             AccountsConstant::CREDIT,
  1482.                             0,
  1483.                             [],
  1484.                             [],
  1485.                             $docHere->getCreatedLoginId()
  1486.                         );
  1487.                         if ($voucher)
  1488.                             $voucher->setTransactionAmount($tot_inv_amount);
  1489.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1490.                         if ($curr_v_ids != null)
  1491.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1492.                         else
  1493.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1494.                         $em->flush();
  1495. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1496.                     }
  1497.                 }
  1498.             }
  1499.             $data = [];
  1500.             $query "SELECT purchase_invoice.* from  purchase_invoice
  1501. where purchase_invoice.purchase_invoice_date ='" $last_refresh_date " 00:00:00' and purchase_invoice.approved=1
  1502.             ";
  1503.             $stmt $em->getConnection()->prepare($query);
  1504.             $stmt->execute();
  1505.             $queryData $stmt->fetchAll();
  1506.             foreach ($queryData as $pi) {
  1507.                 $transDate = new \DateTime($pi['purchase_invoice_date']);
  1508.                 if ($last_refresh_date_obj == '') {
  1509.                     $last_refresh_date_obj $transDate;
  1510.                 } else if ($transDate $last_refresh_date_obj) {
  1511.                     $last_refresh_date_obj $transDate;
  1512.                 }
  1513.                 Accounts::CalibrateProductPriceWithPi($em$pi['purchase_invoice_id'], 1);
  1514.             }
  1515.             $data = [];
  1516.             $query "SELECT expense_invoice.* from  expense_invoice
  1517. where expense_invoice.expense_invoice_date ='" $last_refresh_date " 00:00:00' and expense_invoice.approved=1 and
  1518.             expense_invoice_type_id=1";
  1519.             $stmt $em->getConnection()->prepare($query);
  1520.             $stmt->execute();
  1521.             $queryData $stmt->fetchAll();
  1522.             foreach ($queryData as $ei) {
  1523.                 $transDate = new \DateTime($ei['expense_invoice_date']);
  1524.                 if ($last_refresh_date_obj == '') {
  1525.                     $last_refresh_date_obj $transDate;
  1526.                 } else if ($transDate $last_refresh_date_obj) {
  1527.                     $last_refresh_date_obj $transDate;
  1528.                 }
  1529.                 $grn_ids json_decode($ei['grn_id_list'], true);
  1530.                 if ($grn_ids == null)
  1531.                     $grn_ids = [];
  1532. //                if (!empty($grn_ids)) {
  1533. //
  1534. //
  1535. //                        if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
  1536. //                            $grn = $em->getRepository('ApplicationBundle:Grn')->findBy(array(
  1537. //                                'purchaseOrderId' => $ei->getPurchaseOrderId()
  1538. //                            ));
  1539. //
  1540. //                        }
  1541. //                        else
  1542. //                        {
  1543. //                            $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1544. //                                'purchaseOrderId' => $ei['purchase_order_id']
  1545. //                            ));
  1546. //
  1547. //                            if ($po) {
  1548. //                                $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
  1549. //                            }
  1550. //                            continue; //grn expense will be there anyway
  1551. //                        }
  1552. //
  1553. //
  1554. //
  1555. //                }
  1556.                 Accounts::CalibrateProductPriceWithExpense($em$ei['expense_invoice_id']);
  1557. //                $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
  1558. //                    'purchaseOrderId' => $ei['purchase_order_id']
  1559. //                ));
  1560. //
  1561. //
  1562. //                //first get the total valuation
  1563. //                if ($po) {
  1564. //                    $total_product_value = 0;
  1565. //                    $total_pending_expense = 0;
  1566. //                    $po_item_data = $em->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(array(
  1567. ////                'productId' => $item->getProductId(),
  1568. //                        'purchaseOrderId' => $ei['purchase_order_id']
  1569. //                    ));
  1570. //
  1571. //
  1572. //                    foreach ($po_item_data as $it) {
  1573. ////                    $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1574. ////                        'id' => $item->getProductId()
  1575. ////                    ));
  1576. //
  1577. //                        $poqty = $it->getReceived();
  1578. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
  1579. //                        $total_product_value += (1 * $po_price);
  1580. //
  1581. //
  1582. //                    }
  1583. //
  1584. //
  1585. //                    //now we know the total grn price value. lets get the fraction increase
  1586. //                    $total_pending_expense = $ei['invoice_amount'];
  1587. //                    if ($total_product_value != 0)
  1588. //                        $fraction_increase = ($total_pending_expense) / ($total_product_value);
  1589. //                    else
  1590. //                        $fraction_increase = 0;
  1591. //
  1592. //                    foreach ($po_item_data as $it) {
  1593. //                        $item = $it;
  1594. //                        $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
  1595. //                            'id' => $it->getProductId()
  1596. //                        ));
  1597. //                        if (!$product)
  1598. //                            continue;
  1599. //
  1600. ////                    $items_in_inventory=$em->getRepository('ApplicationBundle:InventoryStorage')->findBy(array(
  1601. ////                        'productId'=>$item->getProductId()
  1602. ////                    ));
  1603. //
  1604. //                        $poqty = $it->getReceived();
  1605. //                        $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
  1606. //
  1607. //                        $existing_qty = $product->getQty();;
  1608. //
  1609. //
  1610. //                        $increased_po_price = ($po_price * $fraction_increase);
  1611. //
  1612. //                        //now lets see homuch is the total price
  1613. //                        $new_purchase_price = $product->getPurchasePrice();
  1614. //
  1615. //                        if ($increased_po_price != 0) {
  1616. //                            $last_grn_item = $em->getRepository('ApplicationBundle:GrnItem')->findOneBy(array(
  1617. //                                'purchaseOrderItemId' => $item->getId()
  1618. //                            ));
  1619. //                            if ($last_grn_item) {
  1620. //
  1621. //                                $data[$last_grn_item->getProductId()][] = array(
  1622. //                                    'date' => $last_refresh_date,
  1623. //
  1624. //                                    'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
  1625. //                                    'entityId' => $ei['expense_invoice_id'],
  1626. //                                    'colorId' => $last_grn_item->getColorId(),
  1627. //                                    'sizeId' => $last_grn_item->getSizeId(),
  1628. //                                    'entityDocHash' => $ei['document_hash'],
  1629. //                                    'qtyAdd' => 0,
  1630. //                                    'qtySub' => 0,
  1631. //                                    'valueAdd' => $increased_po_price,
  1632. ////                                    'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
  1633. ////                    'valueSub' => ($item['qty'] * $item['price']),
  1634. ////                                    'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
  1635. //                                    'valueSub' => 0,
  1636. //                                    'price' => '_UNSET_',
  1637. //                                    'fromWarehouse' => 0,
  1638. //                                    'toWarehouse' => $last_grn_item->getWarehouseId(),
  1639. //                                    'fromWarehouseSub' => 0,
  1640. ////                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1641. //                                    'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
  1642. //                                );
  1643. //
  1644. ////                                Inventory::SetInvClosingBalance($em, $item->getProductId(), $last_grn_item->getWarehouseId(), GeneralConstant::ITEM_TRANSACTION_DIRECTION_IN, (new \DateTime($ei['expense_invoice_date']))->format('Y-m-d'), 0, $increased_po_price, GeneralConstant::WAREHOUSE_ACTION_GOODS, 0, 0, 8);
  1645. ////
  1646. ////                                $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
  1647. ////                                if ($existing_qty != 0)
  1648. ////                                    $new_purchase_price = $total_item_price / $existing_qty;
  1649. //
  1650. //
  1651. //                                $total_pending_expense -= $increased_po_price;
  1652. //                            }
  1653. //                        }
  1654. //                    }
  1655. //
  1656. //
  1657. //
  1658. //
  1659. //
  1660. //
  1661. //                } else {
  1662. //                    continue;
  1663. //                }
  1664.             }
  1665.             $data = [];
  1666.             //____________STOCK_TRANSFER___________________
  1667.             $docEntity "StockTransfer";
  1668.             $docEntityIdField "stockTransferId";
  1669.             $accTransactionDataByDocId = [];
  1670.             $query "SELECT stock_transfer_item.*,  stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from  stock_transfer_item
  1671.               join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
  1672.             where stock_transfer.stock_transfer_date ='" $last_refresh_date " 00:00:00' and stock_transfer.approved=1";
  1673.             $stmt $em->getConnection()->prepare($query);
  1674.             $stmt->execute();
  1675.             $queryData $stmt->fetchAll();
  1676.             $grn_ids = [];
  1677.             foreach ($queryData as $item) {
  1678.                 $data[$item['product_id']][] = array(
  1679.                     'date' => $last_refresh_date,
  1680.                     'transfer_action_type' => $item['transfer_action_type'],
  1681.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  1682.                     'entityId' => $item['stock_transfer_id'],
  1683.                     'colorId' => $item['color_id'],
  1684.                     'sizeId' => $item['size_id'],
  1685.                     'entityDocHash' => $item['document_hash'],
  1686.                     'qtyAdd' => $item['transfer_action_type'] == $item['qty'] : 0,
  1687.                     'qtySub' => $item['qty'],
  1688.                     'valueAdd' => 0,
  1689. //                    'valueSub' => ($item['qty'] * $item['price']),
  1690.                     'valueSub' => '_AUTO_',
  1691.                     'price' => $item['price'],
  1692.                     'fromWarehouse' => $item['warehouse_id'],
  1693.                     'toWarehouse' => $item['transfer_action_type'] == $item['to_warehouse_id'] : 0,
  1694.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  1695. //                    'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
  1696.                     'toWarehouseSub' => $item['transfer_action_type'] == $item['to_warehouse_action_id'] : 0
  1697.                 );
  1698. //                if (!in_array($item['grn_id'], $grn_ids))
  1699. //                    $grn_ids[] = $item['grn_id'];
  1700.             }
  1701.             //now add grns
  1702.             foreach ($data as $key => $item) {
  1703.                 if (!empty($item)) {
  1704.                     foreach ($item as $entry) {
  1705.                         $transDate = new \DateTime($entry['date']);
  1706.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1707.                             $key,
  1708.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1709.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1710.                             $entry['fromWarehouse'],
  1711.                             $entry['toWarehouse'],
  1712.                             $entry['fromWarehouseSub'],
  1713.                             $entry['toWarehouseSub'],
  1714.                             $transDate,
  1715.                             $entry['qtyAdd'],
  1716.                             $entry['qtySub'],
  1717.                             $entry['valueAdd'],
  1718.                             $entry['valueSub'],
  1719.                             $entry['price'],
  1720.                             $this->getLoggedUserCompanyId($request),
  1721.                             0,
  1722.                             $entry['entity'],
  1723.                             $entry['entityId'],
  1724.                             $entry['entityDocHash'],
  1725.                             $entry['transfer_action_type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
  1726.                         );
  1727.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1728.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1729.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1730.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1731.                             "",
  1732.                             'inventory_refresh_debug'1); //last er 1 is append
  1733.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  1734.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  1735.                         if ($entry['transfer_action_type'] == 4) {
  1736.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  1737.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1738.                             else
  1739.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  1740.                         }
  1741.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  1742.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  1743.                         else
  1744.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  1745.                         if ($last_refresh_date_obj == '') {
  1746.                             $last_refresh_date_obj $transDate;
  1747.                         } else if ($transDate $last_refresh_date_obj) {
  1748.                             $last_refresh_date_obj $transDate;
  1749.                         }
  1750.                     }
  1751.                 }
  1752.             }
  1753.             if ($modifyAccTransaction == 1) {
  1754.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  1755.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  1756.                         $docEntityIdField => $docId,
  1757.                     ));;
  1758.                     if ($docHere) {
  1759.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1760.                         if ($curr_v_ids == null)
  1761.                             $curr_v_ids = [];
  1762.                         $skipVids = [];
  1763.                         $toChangeVid 0;
  1764.                         $voucher null;
  1765.                         foreach ($curr_v_ids as $vid) {
  1766.                             if (in_array($vid$skipVids))
  1767.                                 continue;
  1768.                             $skipVids[] = $vid//to prevent duplicate query
  1769.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1770.                                 'transactionId' => $vid,
  1771.                             ));;
  1772.                             if ($voucher) {
  1773.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  1774.                                     $toChangeVid $vid;
  1775.                                 } else {
  1776.                                     continue;
  1777.                                 }
  1778.                             }
  1779.                         }
  1780.                         if ($toChangeVid == 0) {
  1781.                             $toChangeVid Accounts::CreateNewTransaction(0,
  1782.                                 $em,
  1783.                                 $docHere->getStockTransferDate()->format('Y-m-d'),
  1784.                                 0,
  1785.                                 AccountsConstant::VOUCHER_JOURNAL,
  1786.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  1787.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  1788.                                 'JV',
  1789.                                 'GN',
  1790.                                 0,
  1791.                                 Accounts::GetVNoHash($em'jv''gn'0),
  1792.                                 0,
  1793.                                 $docHere->getCreatedLoginId(),
  1794.                                 $docHere->getCompanyId(),
  1795.                                 '',
  1796.                                 0,
  1797.                                 1
  1798.                             );
  1799.                             $em->flush();
  1800.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  1801.                                 'transactionId' => $toChangeVid,
  1802.                             ));;
  1803.                         }
  1804.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  1805.                         $tot_inv_amount 0;
  1806.                         foreach ($transData as $k => $v) {
  1807.                             $tot_inv_amount += ($v);
  1808.                             Accounts::CreateNewTransactionDetails($em,
  1809.                                 '',
  1810.                                 $toChangeVid,
  1811.                                 Generic::CurrToInt($v),
  1812.                                 $k,
  1813.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  1814.                                 $v >= AccountsConstant::DEBIT AccountsConstant::CREDIT,
  1815.                                 0,
  1816.                                 [],
  1817.                                 [],
  1818.                                 $docHere->getCreatedLoginId()
  1819.                             );
  1820.                         }
  1821. //                        $stockReceivedType = $docHere->getType();
  1822.                         $to_balance_head 0;
  1823.                         if ($docHere->getTransferActionType() == 4) {
  1824.                         } else {
  1825.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  1826.                                     'name' => 'inv_on_transit_head')
  1827.                             );
  1828.                             if ($inv_transit_head)
  1829.                                 $to_balance_head $inv_transit_head->getData();
  1830.                         }
  1831.                         if ($to_balance_head != 0) {
  1832.                             Accounts::CreateNewTransactionDetails($em,
  1833.                                 '',
  1834.                                 $toChangeVid,
  1835.                                 Generic::CurrToInt($tot_inv_amount),
  1836.                                 $to_balance_head,
  1837.                                 'In Transit Items for -' $docHere->getDocumentHash(),
  1838.                                 $tot_inv_amount >= AccountsConstant::CREDIT AccountsConstant::DEBIT,
  1839.                                 0,
  1840.                                 [],
  1841.                                 [],
  1842.                                 $docHere->getCreatedLoginId()
  1843.                             );
  1844.                         }
  1845.                         if ($voucher)
  1846.                             $voucher->setTransactionAmount($tot_inv_amount);
  1847.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  1848.                         if ($curr_v_ids != null)
  1849.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  1850.                         else
  1851.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  1852.                         $em->flush();
  1853. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  1854.                     }
  1855.                 }
  1856.             }
  1857.             $data = [];
  1858.             //____________IRR___________________
  1859.             $docEntity "ItemReceivedAndReplacement";
  1860.             $docEntityIdField "itemReceivedAndReplacementId";
  1861.             $accTransactionDataByDocId = [];
  1862.             $query "SELECT irr_item.*,  item_received_replacement.irr_date, item_received_replacement.document_hash from  irr_item
  1863.               join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
  1864.             where item_received_replacement.irr_date ='" $last_refresh_date " 00:00:00' and item_received_replacement.approved=1";
  1865.             $stmt $em->getConnection()->prepare($query);
  1866.             $stmt->execute();
  1867.             $queryData $stmt->fetchAll();
  1868.             $irr_add_data = [];
  1869.             $irr_replace_data = [];
  1870.             $irr_dispose_data = [];
  1871.             foreach ($queryData as $item) {
  1872.                 $irr_add_data[$item['received_product_id']][] = array(
  1873.                     'date' => $last_refresh_date,
  1874.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1875.                     'entityId' => $item['irr_id'],
  1876.                     'colorId' => $item['received_product_color_id'],
  1877.                     'sizeId' => $item['received_product_color_id'],
  1878.                     'entityDocHash' => $item['document_hash'],
  1879.                     'qtyAdd' => $item['received_qty'],
  1880.                     'qtySub' => 0,
  1881.                     'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
  1882.                     'valueSub' => 0,
  1883.                     'price' => $item['received_unit_purchase_price'],
  1884.                     'fromWarehouse' => 0,
  1885.                     'toWarehouse' => $item['received_warehouse_id'],
  1886.                     'fromWarehouseSub' => 0,
  1887.                     'toWarehouseSub' => $item['received_warehouse_action_id']
  1888.                 );
  1889.                 $irr_replace_data[$item['replaced_product_id']][] = array(
  1890.                     'date' => $last_refresh_date,
  1891.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1892.                     'entityId' => $item['irr_id'],
  1893.                     'colorId' => $item['replaced_product_color_id'],
  1894.                     'sizeId' => $item['replaced_product_color_id'],
  1895.                     'entityDocHash' => $item['document_hash'],
  1896.                     'qtyAdd' => 0,
  1897.                     'qtySub' => $item['replaced_qty'],
  1898.                     'valueAdd' => 0,
  1899.                     'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
  1900.                     'price' => $item['replaced_unit_purchase_price'],
  1901.                     'fromWarehouse' => $item['replaced_warehouse_id'],
  1902.                     'toWarehouse' => 0,
  1903.                     'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
  1904.                     'toWarehouseSub' => 0
  1905.                 );
  1906.                 $irr_dispose_data[$item['received_product_id']][] = array(
  1907.                     'date' => $last_refresh_date,
  1908.                     'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  1909.                     'entityId' => $item['irr_id'],
  1910.                     'colorId' => $item['received_product_color_id'],
  1911.                     'sizeId' => $item['received_product_size_id'],
  1912.                     'entityDocHash' => $item['document_hash'],
  1913.                     'qtyAdd' => 0,
  1914.                     'qtySub' => $item['dispose_qty'],
  1915.                     'valueAdd' => 0,
  1916.                     'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
  1917.                     'price' => $item['received_unit_purchase_price'],
  1918.                     'fromWarehouse' => $item['received_warehouse_id'],
  1919.                     'toWarehouse' => 0,
  1920.                     'fromWarehouseSub' => $item['received_warehouse_id'],
  1921.                     'toWarehouseSub' => 0
  1922.                 );
  1923.             }
  1924.             //now add irrs
  1925.             foreach ($irr_add_data as $key => $item) {
  1926.                 if (!empty($item)) {
  1927.                     foreach ($item as $entry) {
  1928.                         $transDate = new \DateTime($entry['date']);
  1929.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1930.                             $key,
  1931.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1932.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1933.                             $entry['fromWarehouse'],
  1934.                             $entry['toWarehouse'],
  1935.                             $entry['fromWarehouseSub'],
  1936.                             $entry['toWarehouseSub'],
  1937.                             $transDate,
  1938.                             $entry['qtyAdd'],
  1939.                             $entry['qtySub'],
  1940.                             $entry['valueAdd'],
  1941.                             $entry['valueSub'],
  1942.                             $entry['price'],
  1943.                             $this->getLoggedUserCompanyId($request),
  1944.                             0,
  1945.                             $entry['entity'],
  1946.                             $entry['entityId'],
  1947.                             $entry['entityDocHash'],
  1948.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  1949.                         );
  1950.                         if ($modifiedData)
  1951.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1952.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1953.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1954.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1955.                                 "",
  1956.                                 'inventory_refresh_debug'1); //last er 1 is append
  1957.                         if ($last_refresh_date_obj == '') {
  1958.                             $last_refresh_date_obj $transDate;
  1959.                         } else if ($transDate $last_refresh_date_obj) {
  1960.                             $last_refresh_date_obj $transDate;
  1961.                         }
  1962.                     }
  1963.                 }
  1964.             }
  1965.             foreach ($irr_replace_data as $key => $item) {
  1966.                 if (!empty($item)) {
  1967.                     foreach ($item as $entry) {
  1968.                         $transDate = new \DateTime($entry['date']);
  1969.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  1970.                             $key,
  1971.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  1972.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  1973.                             $entry['fromWarehouse'],
  1974.                             $entry['toWarehouse'],
  1975.                             $entry['fromWarehouseSub'],
  1976.                             $entry['toWarehouseSub'],
  1977.                             $transDate,
  1978.                             $entry['qtyAdd'],
  1979.                             $entry['qtySub'],
  1980.                             $entry['valueAdd'],
  1981.                             $entry['valueSub'],
  1982.                             $entry['price'],
  1983.                             $this->getLoggedUserCompanyId($request),
  1984.                             0,
  1985.                             $entry['entity'],
  1986.                             $entry['entityId'],
  1987.                             $entry['entityDocHash']);
  1988.                         if ($modifiedData)
  1989.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  1990.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  1991.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  1992.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  1993.                                 "",
  1994.                                 'inventory_refresh_debug'1); //last er 1 is append
  1995.                         if ($last_refresh_date_obj == '') {
  1996.                             $last_refresh_date_obj $transDate;
  1997.                         } else if ($transDate $last_refresh_date_obj) {
  1998.                             $last_refresh_date_obj $transDate;
  1999.                         }
  2000.                     }
  2001.                 }
  2002.             }
  2003.             foreach ($irr_dispose_data as $key => $item) {
  2004.                 if (!empty($item)) {
  2005.                     foreach ($item as $entry) {
  2006.                         $transDate = new \DateTime($entry['date']);
  2007.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2008.                             $key,
  2009.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2010.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2011.                             $entry['fromWarehouse'],
  2012.                             $entry['toWarehouse'],
  2013.                             $entry['fromWarehouseSub'],
  2014.                             $entry['toWarehouseSub'],
  2015.                             $transDate,
  2016.                             $entry['qtyAdd'],
  2017.                             $entry['qtySub'],
  2018.                             $entry['valueAdd'],
  2019.                             $entry['valueSub'],
  2020.                             $entry['price'],
  2021.                             $this->getLoggedUserCompanyId($request),
  2022.                             0,
  2023.                             $entry['entity'],
  2024.                             $entry['entityId'],
  2025.                             $entry['entityDocHash'],
  2026.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2027.                         );
  2028.                         if ($modifiedData)
  2029.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2030.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2031.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2032.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2033.                                 "",
  2034.                                 'inventory_refresh_debug'1); //last er 1 is append
  2035.                         if ($last_refresh_date_obj == '') {
  2036.                             $last_refresh_date_obj $transDate;
  2037.                         } else if ($transDate $last_refresh_date_obj) {
  2038.                             $last_refresh_date_obj $transDate;
  2039.                         }
  2040.                     }
  2041.                 }
  2042.             }
  2043.             $data = [];
  2044.             //____________DELIVERY_RECEIPT___________________
  2045.             $docEntity "DeliveryReceipt";
  2046.             $docEntityIdField "deliveryReceiptId";
  2047.             $accTransactionDataByDocId = [];
  2048.             $query "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from  delivery_receipt_item
  2049.               join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
  2050.             where delivery_receipt.delivery_receipt_date ='" $last_refresh_date " 00:00:00' and delivery_receipt.approved=1";
  2051.             $stmt $em->getConnection()->prepare($query);
  2052.             $stmt->execute();
  2053.             $queryData $stmt->fetchAll();
  2054.             foreach ($queryData as $item) {
  2055.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  2056.                     ->findOneBy(
  2057.                         array(
  2058.                             'id' => $item['product_id']
  2059.                         )
  2060.                     );
  2061.                 $curr_purchase_price $product->getPurchasePrice();
  2062.                 if ($item['skip_inventory_hit'] != 1) {
  2063.                     $data[$item['product_id']][] = array(
  2064.                         'date' => $last_refresh_date,
  2065.                         'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  2066.                         'entityId' => $item['delivery_receipt_id'],
  2067.                         'colorId' => $item['color_id'],
  2068.                         'sizeId' => $item['size_id'],
  2069.                         'entityDocHash' => $item['document_hash'],
  2070.                         'qtyAdd' => 0,
  2071.                         'qtySub' => ($item['qty'] * $item['unit_multiplier']),
  2072.                         'valueAdd' => 0,
  2073.                         'valueSub' => '_AUTO_',
  2074.                         'price' => $curr_purchase_price,
  2075.                         'fromWarehouse' => $item['warehouse_id'],
  2076.                         'toWarehouse' => 0,
  2077.                         'fromWarehouseSub' => $item['warehouse_action_id'] != null $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
  2078.                         'toWarehouseSub' => 0
  2079.                     );
  2080.                 }
  2081.                 $get_kids_sql "UPDATE `delivery_receipt_item` SET current_purchase_price='" $curr_purchase_price "' WHERE id=" $item['id'] . ";";
  2082.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  2083.                 $stmt->execute();
  2084.             }
  2085.             foreach ($data as $key => $item) {
  2086.                 if (!empty($item)) {
  2087.                     foreach ($item as $entry) {
  2088.                         $transDate = new \DateTime($entry['date']);
  2089.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2090.                             $key,
  2091.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2092.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2093.                             $entry['fromWarehouse'],
  2094.                             $entry['toWarehouse'],
  2095.                             $entry['fromWarehouseSub'],
  2096.                             $entry['toWarehouseSub'],
  2097.                             $transDate,
  2098.                             $entry['qtyAdd'],
  2099.                             $entry['qtySub'],
  2100.                             $entry['valueAdd'],
  2101.                             $entry['valueSub'],
  2102.                             $entry['price'],
  2103.                             $this->getLoggedUserCompanyId($request),
  2104.                             0,
  2105.                             $entry['entity'],
  2106.                             $entry['entityId'],
  2107.                             $entry['entityDocHash'],
  2108.                             GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
  2109.                         );
  2110.                         if ($modifiedData)
  2111.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2112.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2113.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2114.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2115.                                 "",
  2116.                                 'inventory_refresh_debug'1); //last er 1 is append
  2117.                         if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2118.                             $accTransactionDataByDocId[$entry['entityId']] = array();
  2119.                         if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2120.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2121.                         else
  2122.                             $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2123.                         if ($last_refresh_date_obj == '') {
  2124.                             $last_refresh_date_obj $transDate;
  2125.                         } else if ($transDate $last_refresh_date_obj) {
  2126.                             $last_refresh_date_obj $transDate;
  2127.                         }
  2128.                     }
  2129.                 }
  2130.             }
  2131.             if ($modifyAccTransaction == 1) {
  2132.                 //for now we are suuming there is only receipt without confirmation needed
  2133.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2134.                     $docHereDr $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2135.                         $docEntityIdField => $docId,
  2136.                     ));;
  2137.                     $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2138.                         array(
  2139.                             'salesOrderId' => $docHereDr->getSalesOrderId()
  2140.                         )
  2141.                     );
  2142.                     $query $em->getRepository('ApplicationBundle:SalesInvoice')
  2143.                         ->createQueryBuilder('p');
  2144.                     $query->where('p.salesOrderId = :soID')
  2145.                         ->setParameter('soID'$docHereDr->getSalesOrderId());
  2146.                     $query->andWhere("p.deliveryReceiptIds LIKE '%" $docId "%' ");
  2147.                     $query->setMaxResults(1);
  2148.                     $results $query->getQuery()->getResult();
  2149.                     $docHere null;
  2150.                     if (!empty($results))
  2151.                         $docHere $results[0];
  2152.                     if ($docHere) {
  2153.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2154.                         if ($curr_v_ids == null)
  2155.                             $curr_v_ids = [];
  2156.                         $skipVids = [];
  2157.                         $toChangeVid 0;
  2158.                         $voucher null;
  2159.                         foreach ($curr_v_ids as $vid) {
  2160.                             if (in_array($vid$skipVids))
  2161.                                 continue;
  2162.                             $skipVids[] = $vid//to prevent duplicate query
  2163.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2164.                                 'transactionId' => $vid,
  2165.                             ));;
  2166.                             if ($voucher) {
  2167.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2168.                                     $toChangeVid $vid;
  2169.                                 } else {
  2170.                                     continue;
  2171.                                 }
  2172.                                 if (strpos($voucher->getDescription(), 'Inventory') !== false) {
  2173. //                                    echo "Word Found!";
  2174.                                     $toChangeVid $vid;
  2175.                                 } else {
  2176.                                     continue;
  2177.                                 }
  2178.                             }
  2179.                         }
  2180.                         if ($toChangeVid == 0) {
  2181.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2182.                                 $em,
  2183.                                 $docHere->getSalesInvoiceDate()->format('Y-m-d'),
  2184.                                 0,
  2185.                                 AccountsConstant::VOUCHER_JOURNAL,
  2186.                                 'Journal For Inventory balance for Sales Invoice ' $docHere->getDocumentHash(),
  2187.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2188.                                 'JV',
  2189.                                 'GN',
  2190.                                 0,
  2191.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2192.                                 0,
  2193.                                 $docHere->getCreatedLoginId(),
  2194.                                 $docHere->getCompanyId(),
  2195.                                 '',
  2196.                                 0,
  2197.                                 1,
  2198.                                 0''$so->getBranchId(),
  2199.                                 AccountsConstant::INVOICE_REVENUE_JOURNAL,
  2200.                                 array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
  2201.                             );
  2202.                             $em->flush();
  2203.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2204.                                 'transactionId' => $toChangeVid,
  2205.                             ));;
  2206.                         }
  2207. //                        DeleteDocument::AccTransactions($em, $toChangeVid, 0);
  2208.                         //now remove cogs or inventory related transactions
  2209.                         $voucherDetails $em->getRepository('ApplicationBundle:AccTransactionDetails')->findBy(array(
  2210.                             'transactionId' => $toChangeVid,
  2211.                         ));;
  2212.                         foreach ($voucherDetails as $vdtls) {
  2213.                             if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
  2214.                                 $em->remove($vdtls);
  2215.                                 $em->flush();
  2216.                             }
  2217.                             if ($cogs_head == $vdtls->getAccountsHeadId()) {
  2218.                                 $em->remove($vdtls);
  2219.                                 $em->flush();
  2220.                             }
  2221.                         }
  2222.                         $tot_inv_amount 0;
  2223.                         foreach ($transData as $k => $v) {
  2224.                             $tot_inv_amount += ($v);
  2225.                             Accounts::CreateNewTransactionDetails($em,
  2226.                                 '',
  2227.                                 $toChangeVid,
  2228.                                 Generic::CurrToInt($v),
  2229.                                 $k,
  2230.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2231.                                 AccountsConstant::DEBIT,
  2232.                                 0,
  2233.                                 [],
  2234.                                 [],
  2235.                                 $docHere->getCreatedLoginId()
  2236.                             );
  2237.                         }
  2238. //                        $stockReceivedType = $docHere->getType();
  2239.                         $to_balance_head 0;
  2240. //                        if ($docHere->getTransferActionType() == 4)
  2241.                         if (1) {
  2242.                         } else {
  2243.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2244.                                     'name' => 'inv_on_transit_head')
  2245.                             );
  2246.                             if ($inv_transit_head)
  2247.                                 $to_balance_head $inv_transit_head->getData();
  2248.                         }
  2249.                         if ($to_balance_head != 0) {
  2250.                             Accounts::CreateNewTransactionDetails($em,
  2251.                                 '',
  2252.                                 $toChangeVid,
  2253.                                 Generic::CurrToInt($tot_inv_amount),
  2254.                                 $to_balance_head,
  2255.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2256.                                 AccountsConstant::CREDIT,
  2257.                                 0,
  2258.                                 [],
  2259.                                 [],
  2260.                                 $docHere->getCreatedLoginId()
  2261.                             );
  2262.                         }
  2263.                         if ($voucher)
  2264.                             $voucher->setTransactionAmount($tot_inv_amount);
  2265.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2266.                         if ($curr_v_ids != null)
  2267.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2268.                         else
  2269.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2270.                         $em->flush();
  2271. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2272.                     }
  2273.                 }
  2274.             }
  2275.             $data = [];
  2276.             //____________STOCK_CONSUMPTION___________________
  2277.             $docEntity "StockConsumptionNote";
  2278.             $docEntityIdField "stockConsumptionNoteId";
  2279.             $accTransactionDataByDocId = [];
  2280.             $query "SELECT stock_consumption_note_item.*,  stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
  2281.               from  stock_consumption_note_item
  2282.               join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
  2283.             where stock_consumption_note.stock_consumption_note_date ='" $last_refresh_date " 00:00:00' and stock_consumption_note.approved=1";
  2284.             $stmt $em->getConnection()->prepare($query);
  2285.             $stmt->execute();
  2286.             $queryData $stmt->fetchAll();
  2287.             $consumption_data = [];
  2288.             $produced_data = [];
  2289.             $checked_stcm_ids = [];
  2290.             foreach ($queryData as $item) {
  2291. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2292. //                    ->findOneBy(
  2293. //                        array(
  2294. //                            'id'=>$item['product_id']
  2295. //                        )
  2296. //                    );
  2297. //
  2298. //                $curr_purchase_price=$product->getPurchasePrice();
  2299.                 if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
  2300.                     $conversion_data json_decode($item['data'], true);
  2301.                     if ($conversion_data == null)
  2302.                         $conversion_data = [];
  2303.                     if (isset($conversion_data['conversionData'])) {
  2304.                         if (isset($conversion_data['conversionData']['converted_products'])) {
  2305.                             $curr_spec_data $conversion_data['conversionData'];
  2306.                             foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
  2307.                                 $consumption_data[$val][] = array(
  2308.                                     'date' => $last_refresh_date,
  2309.                                     'type' => 2,
  2310.                                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2311.                                     'entityId' => $item['stock_consumption_note_id'],
  2312.                                     'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? ($curr_spec_data['converted_product_colors'][$pika_key]) : 0,
  2313.                                     'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? ($curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
  2314.                                     'entityDocHash' => $item['document_hash'],
  2315.                                     'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2316.                                     'qtySub' => 0,
  2317.                                     'valueAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key] * $curr_spec_data['converted_product_units'][$pika_key]) : 0,
  2318.                                     'valueSub' => 0,
  2319.                                     'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
  2320.                                     'fromWarehouse' => 0,
  2321.                                     'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? ($curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
  2322.                                     'fromWarehouseSub' => 0,
  2323.                                     'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? ($curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
  2324.                                 );
  2325.                             }
  2326.                         }
  2327.                     }
  2328. //                    if(isset($conversion_data['expenseCost'] ))
  2329. //                    if(isset($conversion_data['expenseCost']['expense_heads'] ))
  2330. //                    {
  2331. //                        $curr_spec_data=$conversion_data['expenseCost'];
  2332. //                        foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
  2333. //                        {
  2334. //
  2335. //                            $consumption_data[$val][] = array(
  2336. //                                'date' => $last_refresh_date,
  2337. //                                'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2338. //                                'entityId' => $item['stock_consumption_note_id'],
  2339. //                                'entityDocHash' => $item['document_hash'],
  2340. //                                'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2341. //                                'qtySub' => 0,
  2342. //                                'valueAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?($curr_spec_data['converted_product_unit_price'][$pika_key]*$curr_spec_data['converted_product_units'][$pika_key]):0,
  2343. //                                'valueSub' => 0,
  2344. //                                'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
  2345. //                                'fromWarehouse' => 0,
  2346. //                                'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
  2347. //                                'fromWarehouseSub' => 0,
  2348. //                                'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
  2349. //                            );
  2350. //                        }
  2351. //                    }
  2352.                     $checked_stcm_ids[] = $item['stock_consumption_note_id'];
  2353.                 }
  2354.                 $consumption_data[$item['product_id']][] = array(
  2355.                     'date' => $last_refresh_date,
  2356.                     'type' => 1,
  2357.                     'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  2358.                     'entityId' => $item['stock_consumption_note_id'],
  2359.                     'colorId' => $item['color_id'],
  2360.                     'sizeId' => $item['size_id'],
  2361.                     'entityDocHash' => $item['document_hash'],
  2362.                     'qtyAdd' => 0,
  2363.                     'qtySub' => ($item['qty'] * 1),
  2364.                     'valueAdd' => 0,
  2365.                     'valueSub' => (($item['qty']) * ($item['price'])),
  2366.                     'price' => $item['price'],
  2367.                     'fromWarehouse' => $item['warehouse_id'],
  2368.                     'toWarehouse' => 0,
  2369.                     'fromWarehouseSub' => $item['warehouse_action_id'],
  2370.                     'toWarehouseSub' => 0
  2371.                 );
  2372. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2373. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2374. //                $stmt->execute();
  2375.             }
  2376.             foreach ($consumption_data as $key => $item) {
  2377.                 if (!empty($item)) {
  2378.                     foreach ($item as $entry) {
  2379.                         $transDate = new \DateTime($entry['date']);
  2380.                         $modifiedData Inventory::addItemToInventoryCompact($em,
  2381.                             $key,
  2382.                             isset($entry['colorId']) ? $entry['colorId'] : 0,
  2383.                             isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2384.                             $entry['fromWarehouse'],
  2385.                             $entry['toWarehouse'],
  2386.                             $entry['fromWarehouseSub'],
  2387.                             $entry['toWarehouseSub'],
  2388.                             $transDate,
  2389.                             $entry['qtyAdd'],
  2390.                             $entry['qtySub'],
  2391.                             $entry['valueAdd'],
  2392.                             $entry['valueSub'],
  2393.                             $entry['price'],
  2394.                             $this->getLoggedUserCompanyId($request),
  2395.                             0,
  2396.                             $entry['entity'],
  2397.                             $entry['entityId'],
  2398.                             $entry['entityDocHash'],
  2399.                             $entry['type'] == GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
  2400.                         );
  2401.                         System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2402.                             "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2403.                             "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2404.                             "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2405.                             "",
  2406.                             'inventory_refresh_debug'1); //last er 1 is append
  2407.                         if ($last_refresh_date_obj == '') {
  2408.                             $last_refresh_date_obj $transDate;
  2409.                         } else if ($transDate $last_refresh_date_obj) {
  2410.                             $last_refresh_date_obj $transDate;
  2411.                         }
  2412.                     }
  2413.                 }
  2414.             }
  2415.             $data = [];
  2416.             //____________PRODUCTION___________________
  2417.             $docEntity "Production";
  2418.             $docEntityIdField "productionId";
  2419.             $accTransactionDataByDocId = [];
  2420.             $consumedAmountByProductionId = [];
  2421.             $query "SELECT * from production_process_settings
  2422.             where approved=1 order by production_process_settings_id asc  ";
  2423.             $stmt $em->getConnection()->prepare($query);
  2424.             $stmt->execute();
  2425.             $processList $stmt->fetchAll();
  2426. //            $processList=[];
  2427.             foreach ($processList as $process) {
  2428.                 $query "SELECT production_entry_item.*,  production.production_date, production.document_hash
  2429.               from  production_entry_item
  2430.               join production on production_entry_item.production_id=production.production_id
  2431.             where production_entry_item.process_settings_id =" $process['production_process_settings_id'] . " and production.production_date ='" $last_refresh_date " 00:00:00' and production.approved=1 order by production_id asc  ";
  2432.                 $stmt $em->getConnection()->prepare($query);
  2433.                 $stmt->execute();
  2434.                 $queryData $stmt->fetchAll();
  2435.                 $produced_data = [];
  2436.                 $rejected_data = [];
  2437.                 $consumed_data = [];
  2438.                 foreach ($queryData as $item) {
  2439. //                $product=$em->getRepository('ApplicationBundle:InvProducts')
  2440. //                    ->findOneBy(
  2441. //                        array(
  2442. //                            'id'=>$item['product_id']
  2443. //                        )
  2444. //                    );
  2445. //
  2446. //                $curr_purchase_price=$product->getPurchasePrice();
  2447.                     if ($item['price'] == '')
  2448.                         $item['price'] = 0;
  2449.                     if ($item['price'] < 0)
  2450.                         $item['price'] = 0;
  2451.                     $item['production_nature_id'];
  2452.                     $consumed_data[$item['product_id']][] = array(
  2453.                         'date' => $last_refresh_date,
  2454.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2455.                         'entityId' => $item['production_id'],
  2456.                         'colorId' => $item['color_id'],
  2457.                         'sizeId' => $item['size_id'],
  2458.                         'entityDocHash' => $item['document_hash'],
  2459.                         'qtyAdd' => 0,
  2460.                         'qtySub' => ($item['additional_consumed_qty'] * 1) + ($item['consumed_qty']),
  2461.                         'valueAdd' => 0,
  2462.                         'valueSub' => '_AUTO_',
  2463.                         'price' => $item['price'],
  2464.                         'fromWarehouse' => $item['warehouse_id'],
  2465.                         'toWarehouse' => 0,
  2466.                         'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
  2467.                         'toWarehouseSub' => 0,
  2468.                         'production_nature_id' => $item['production_nature_id'],
  2469.                     );
  2470.                     $produced_data[$item['product_id']][] = array(
  2471.                         'date' => $last_refresh_date,
  2472.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2473.                         'entityId' => $item['production_id'],
  2474.                         'colorId' => $item['color_id'],
  2475.                         'sizeId' => $item['size_id'],
  2476.                         'entityDocHash' => $item['document_hash'],
  2477.                         'qtyAdd' => ($item['accepted_qty'] * 1),
  2478.                         'qtySub' => 0,
  2479.                         'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
  2480.                         'valueSub' => 0,
  2481.                         'price' => $item['price'],
  2482.                         'fromWarehouse' => 0,
  2483.                         'toWarehouse' => $item['warehouse_id'],
  2484.                         'fromWarehouseSub' => 0,
  2485.                         'toWarehouseSub' => $item['produced_item_action_tag_id'],
  2486.                         'production_nature_id' => $item['production_nature_id'],
  2487.                     );
  2488.                     $rejected_data[$item['product_id']][] = array(
  2489.                         'date' => $last_refresh_date,
  2490.                         'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
  2491.                         'entityId' => $item['production_id'],
  2492.                         'colorId' => $item['color_id'],
  2493.                         'sizeId' => $item['size_id'],
  2494.                         'entityDocHash' => $item['document_hash'],
  2495.                         'qtyAdd' => ($item['rejected_qty'] * 1),
  2496.                         'qtySub' => 0,
  2497.                         'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
  2498.                         'valueSub' => 0,
  2499.                         'price' => $item['price'],
  2500.                         'fromWarehouse' => 0,
  2501.                         'toWarehouse' => $item['warehouse_id'],
  2502.                         'fromWarehouseSub' => 0,
  2503.                         'toWarehouseSub' => $item['rejected_item_action_tag_id'],
  2504.                         'production_nature_id' => $item['production_nature_id'],
  2505.                     );
  2506. //                $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
  2507. //                $stmt = $em->getConnection()->prepare($get_kids_sql);
  2508. //                $stmt->execute();
  2509.                 }
  2510.                 foreach ($consumed_data as $key => $item) {
  2511.                     if (!empty($item)) {
  2512.                         foreach ($item as $entry) {
  2513.                             $transDate = new \DateTime($entry['date']);
  2514.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2515.                                 $key,
  2516.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2517.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2518.                                 $entry['fromWarehouse'],
  2519.                                 $entry['toWarehouse'],
  2520.                                 $entry['fromWarehouseSub'],
  2521.                                 $entry['toWarehouseSub'],
  2522.                                 $transDate,
  2523.                                 $entry['qtyAdd'],
  2524.                                 $entry['qtySub'],
  2525.                                 $entry['valueAdd'],
  2526.                                 $entry['valueSub'],
  2527.                                 $entry['price'],
  2528.                                 $this->getLoggedUserCompanyId($request),
  2529.                                 0,
  2530.                                 $entry['entity'],
  2531.                                 $entry['entityId'],
  2532.                                 $entry['entityDocHash'],
  2533.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
  2534.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2535.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2536.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2537.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2538.                                 "",
  2539.                                 'inventory_refresh_debug'1); //last er 1 is append
  2540.                             if (!isset($consumedAmountByProductionId[$entry['entityId']]))
  2541.                                 $consumedAmountByProductionId[$entry['entityId']] = ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2542.                             else
  2543.                                 $consumedAmountByProductionId[$entry['entityId']] += ($entry['qtySub'] * $modifiedData['slot_cost_price']);
  2544.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2545.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2546.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2547.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2548.                             else
  2549.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2550.                             if ($last_refresh_date_obj == '') {
  2551.                                 $last_refresh_date_obj $transDate;
  2552.                             } else if ($transDate $last_refresh_date_obj) {
  2553.                                 $last_refresh_date_obj $transDate;
  2554.                             }
  2555.                         }
  2556.                     }
  2557.                 }
  2558.                 foreach ($produced_data as $key => $item) {
  2559.                     if (!empty($item)) {
  2560.                         foreach ($item as $entry) {
  2561.                             $transDate = new \DateTime($entry['date']);
  2562.                             $productionNature $entry['production_nature_id'];
  2563.                             if (in_array($productionNature, [12])) {
  2564.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2565.                                     $key,
  2566.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2567.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2568.                                     $entry['fromWarehouse'],
  2569.                                     $entry['toWarehouse'],
  2570.                                     $entry['fromWarehouseSub'],
  2571.                                     $entry['toWarehouseSub'],
  2572.                                     $transDate,
  2573.                                     $entry['qtyAdd'],
  2574.                                     $entry['qtySub'],
  2575. //                                $entry['valueAdd'],
  2576.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2577.                                     $entry['valueSub'],
  2578.                                     $entry['price'],
  2579.                                     $this->getLoggedUserCompanyId($request),
  2580.                                     0,
  2581.                                     $entry['entity'],
  2582.                                     $entry['entityId'],
  2583.                                     $entry['entityDocHash'],
  2584.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2585.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2586.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2587.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2588.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2589.                                     "",
  2590.                                     'inventory_refresh_debug'1); //last er 1 is append
  2591.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2592.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2593.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2594.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2595.                                 else
  2596.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2597. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2598. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2599. //                            else
  2600. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2601.                             } else {
  2602.                                 $modifiedData Inventory::addItemToInventoryCompact($em,
  2603.                                     $key,
  2604.                                     isset($entry['colorId']) ? $entry['colorId'] : 0,
  2605.                                     isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2606.                                     $entry['fromWarehouse'],
  2607.                                     $entry['toWarehouse'],
  2608.                                     $entry['fromWarehouseSub'],
  2609.                                     $entry['toWarehouseSub'],
  2610.                                     $transDate,
  2611.                                     0,
  2612.                                     0,
  2613. //                                $entry['valueAdd'],
  2614.                                     $consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
  2615.                                     0,
  2616.                                     $entry['price'],
  2617.                                     $this->getLoggedUserCompanyId($request),
  2618.                                     0,
  2619.                                     $entry['entity'],
  2620.                                     $entry['entityId'],
  2621.                                     $entry['entityDocHash'],
  2622.                                     GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2623.                                 System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2624.                                     "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2625.                                     "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2626.                                     "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2627.                                     "",
  2628.                                     'inventory_refresh_debug'1); //last er 1 is append
  2629.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2630.                                     $accTransactionDataByDocId[$entry['entityId']] = array();
  2631.                                 if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2632.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2633.                                 else
  2634.                                     $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ($entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2635. //                            if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
  2636. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
  2637. //                            else
  2638. //                                $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
  2639.                             }
  2640.                             if ($last_refresh_date_obj == '') {
  2641.                                 $last_refresh_date_obj $transDate;
  2642.                             } else if ($transDate $last_refresh_date_obj) {
  2643.                                 $last_refresh_date_obj $transDate;
  2644.                             }
  2645.                         }
  2646.                     }
  2647.                 }
  2648.                 foreach ($rejected_data as $key => $item) {
  2649.                     if (!empty($item)) {
  2650.                         foreach ($item as $entry) {
  2651.                             $transDate = new \DateTime($entry['date']);
  2652.                             $modifiedData Inventory::addItemToInventoryCompact($em,
  2653.                                 $key,
  2654.                                 isset($entry['colorId']) ? $entry['colorId'] : 0,
  2655.                                 isset($entry['sizeId']) ? $entry['sizeId'] : 0,
  2656.                                 $entry['fromWarehouse'],
  2657.                                 $entry['toWarehouse'],
  2658.                                 $entry['fromWarehouseSub'],
  2659.                                 $entry['toWarehouseSub'],
  2660.                                 $transDate,
  2661.                                 $entry['qtyAdd'],
  2662.                                 $entry['qtySub'],
  2663.                                 $entry['valueAdd'],
  2664.                                 $entry['valueSub'],
  2665.                                 $entry['price'],
  2666.                                 $this->getLoggedUserCompanyId($request),
  2667.                                 0,
  2668.                                 $entry['entity'],
  2669.                                 $entry['entityId'],
  2670.                                 $entry['entityDocHash'],
  2671.                                 GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
  2672.                             System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
  2673.                                 "--- Product # _" $modifiedData['productId'] . "_ " $modifiedData['productName'] . "" .
  2674.                                 "----- Modified Price: " $modifiedData['modified_price'] . " " .
  2675.                                 "----- Document # _" $modifiedData['entityName'] . "_ " $modifiedData['entityDocHash'] . "" .
  2676.                                 "",
  2677.                                 'inventory_refresh_debug'1); //last er 1 is append
  2678.                             if (!isset($accTransactionDataByDocId[$entry['entityId']]))
  2679.                                 $accTransactionDataByDocId[$entry['entityId']] = array();
  2680.                             if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
  2681.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
  2682.                             else
  2683.                                 $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
  2684.                             if ($last_refresh_date_obj == '') {
  2685.                                 $last_refresh_date_obj $transDate;
  2686.                             } else if ($transDate $last_refresh_date_obj) {
  2687.                                 $last_refresh_date_obj $transDate;
  2688.                             }
  2689.                         }
  2690.                     }
  2691.                 }
  2692.             }
  2693.             if ($modifyAccTransaction == 1) {
  2694.                 foreach ($accTransactionDataByDocId as $docId => $transData) {
  2695.                     $docHere $em->getRepository('ApplicationBundle:' $docEntity)->findOneBy(array(
  2696.                         $docEntityIdField => $docId,
  2697.                     ));;
  2698.                     if ($docHere) {
  2699.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2700.                         if ($curr_v_ids == null)
  2701.                             $curr_v_ids = [];
  2702.                         $skipVids = [];
  2703.                         $toChangeVid 0;
  2704.                         $voucher null;
  2705.                         foreach ($curr_v_ids as $vid) {
  2706.                             if (in_array($vid$skipVids))
  2707.                                 continue;
  2708.                             $skipVids[] = $vid//to prevent duplicate query
  2709.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2710.                                 'transactionId' => $vid,
  2711.                             ));;
  2712.                             if ($voucher) {
  2713.                                 if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
  2714.                                     $toChangeVid $vid;
  2715.                                 } else {
  2716.                                     continue;
  2717.                                 }
  2718.                             }
  2719.                         }
  2720.                         if ($toChangeVid == 0) {
  2721.                             $toChangeVid Accounts::CreateNewTransaction(0,
  2722.                                 $em,
  2723.                                 $docHere->getProductionDate()->format('Y-m-d'),
  2724.                                 0,
  2725.                                 AccountsConstant::VOUCHER_JOURNAL,
  2726.                                 'Journal For Stock Transfer Inventory Ledger Hit for Document- ' $docHere->getDocumentHash(),
  2727.                                 'JV/GN/0/' Accounts::GetVNoHash($em'jv''gn'0),
  2728.                                 'JV',
  2729.                                 'GN',
  2730.                                 0,
  2731.                                 Accounts::GetVNoHash($em'jv''gn'0),
  2732.                                 0,
  2733.                                 $docHere->getCreatedLoginId(),
  2734.                                 $docHere->getCompanyId(),
  2735.                                 '',
  2736.                                 0,
  2737.                                 1
  2738.                             );
  2739.                             $em->flush();
  2740.                             $voucher $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  2741.                                 'transactionId' => $toChangeVid,
  2742.                             ));;
  2743.                         }
  2744.                         DeleteDocument::AccTransactions($em$toChangeVid0);
  2745.                         $tot_inv_amount 0;
  2746.                         foreach ($transData as $k => $v) {
  2747.                             $tot_inv_amount += ($v);
  2748.                             Accounts::CreateNewTransactionDetails($em,
  2749.                                 '',
  2750.                                 $toChangeVid,
  2751.                                 Generic::CurrToInt($v),
  2752.                                 $k,
  2753.                                 $v >= 'Inventory Inward For - ' $docHere->getDocumentHash() : 'Inventory Outward For - ' $docHere->getDocumentHash(),
  2754.                                 AccountsConstant::DEBIT,
  2755.                                 0,
  2756.                                 [],
  2757.                                 [],
  2758.                                 $docHere->getCreatedLoginId()
  2759.                             );
  2760.                         }
  2761. //                        $stockReceivedType = $docHere->getType();
  2762.                         $to_balance_head 0;
  2763. //                        if ($docHere->getTransferActionType() == 4)
  2764.                         if (1) {
  2765.                         } else {
  2766.                             $inv_transit_head $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2767.                                     'name' => 'inv_on_transit_head')
  2768.                             );
  2769.                             if ($inv_transit_head)
  2770.                                 $to_balance_head $inv_transit_head->getData();
  2771.                         }
  2772.                         if ($to_balance_head != 0) {
  2773.                             Accounts::CreateNewTransactionDetails($em,
  2774.                                 '',
  2775.                                 $toChangeVid,
  2776.                                 Generic::CurrToInt($tot_inv_amount),
  2777.                                 $to_balance_head,
  2778.                                 $tot_inv_amount >= 'Inventory Outward For - ' $docHere->getDocumentHash() : 'Inventory in transit For - ' $docHere->getDocumentHash(),
  2779.                                 AccountsConstant::CREDIT,
  2780.                                 0,
  2781.                                 [],
  2782.                                 [],
  2783.                                 $docHere->getCreatedLoginId()
  2784.                             );
  2785.                         }
  2786.                         if ($voucher)
  2787.                             $voucher->setTransactionAmount($tot_inv_amount);
  2788.                         $curr_v_ids json_decode($docHere->getVoucherIds(), true);
  2789.                         if ($curr_v_ids != null)
  2790.                             $docHere->setVoucherIds(json_encode(array_merge($curr_v_idsarray_diff([$toChangeVid], $curr_v_ids))));
  2791.                         else
  2792.                             $docHere->setVoucherIds(json_encode([$toChangeVid]));
  2793.                         $em->flush();
  2794. //                        System::UpdatePostDatedTransactionById($em, $toChangeVid);
  2795.                     }
  2796.                 }
  2797.             }
  2798.             if ($terminate == 0) {
  2799.                 return new JsonResponse(array(
  2800.                     "success" => true,
  2801.                     "last_refresh_date" => $last_refresh_date,
  2802.                     "inventory_refreshed" => $refreshed_opening
  2803.                 ));
  2804.             } else {
  2805.                 return new JsonResponse(array(
  2806.                     "success" => false,
  2807.                     "last_refresh_date" => $last_refresh_date,
  2808.                     "inventory_refreshed" => $refreshed_opening
  2809.                 ));
  2810.             }
  2811.         }
  2812.         return new JsonResponse(array(
  2813.             "success" => false,
  2814.             "last_refresh_date" => $last_refresh_date,
  2815.             "inventory_refreshed" => $refreshed_opening
  2816.         ));
  2817.         //2 .now make an array with necessary data based on challan and grn for now willl need consumption later
  2818.         //broken into transactions not closing
  2819.         //structure---> $data['productId']=array(
  2820.         //'date'=>'2017-09-02 00:00:00'
  2821.         //'qtyAdd'=>'2'
  2822.         //'qtySub'=>'0'
  2823.         //'valueAdd'=>'2000'
  2824.         //'valueSub'=>'0'
  2825.         //'fromWarehouse'=>'0'
  2826.         //'toWarehouse'=>'0'
  2827.         //'fromWarehouseSub'=>'0'
  2828.         //'toWarehouseSub'=>'0'
  2829.         //)
  2830.         //
  2831.     }
  2832.     public function OpeningItemAction(Request $request)
  2833.     {
  2834.         $em $this->getDoctrine()->getManager();
  2835.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  2836.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  2837.         if ($request->isMethod('POST')) {
  2838.             $pp trim($request->request->get('purchasePrice'));
  2839. //replace comma with space
  2840.             $pp str_replace(","""$pp);
  2841.             if ($request->request->get('productId') != '') {
  2842.                 foreach ($request->request->get('warehouseId') as $key => $value) {
  2843.                     $data = array(
  2844.                         'productId' => $request->request->get('productId'),
  2845.                         'warehouseId' => $request->request->get('warehouseId')[$key],
  2846.                         'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
  2847.                         'purchasePrice' => $pp,
  2848.                         'date' => new \DateTime($request->request->get('date')),
  2849.                         'qty' => $request->request->get('qty')[$key],
  2850.                     );
  2851.                     $transDate = new \DateTime($request->request->get('date'));
  2852.                     $new = new InvItemInOut();
  2853.                     $new->setProductId($request->request->get('productId'));
  2854.                     $new->setWarehouseId($request->request->get('warehouseId')[$key]);
  2855.                     $new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
  2856.                     $new->setActionTagId($request->request->get('warehouseActionId')[$key]);
  2857.                     $new->setTransactionDate($transDate);
  2858.                     $new->setQty($request->request->get('qty')[$key]);
  2859.                     $new->setPrice($pp);
  2860.                     $new->setAmount($request->request->get('qty')[$key] * $pp);
  2861.                     $new->setEntity(0);// opening =0
  2862.                     $new->setEntityId(0);// opening =0
  2863.                     $new->setDebitCreditHeadId(0);// opening =0
  2864.                     $new->setVoucherIds(null);// opening =0
  2865.                     $em->persist($new);
  2866.                     $em->flush();
  2867. //                    $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
  2868.                     Inventory::AddOpeningInventoryStock($em$data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2869.                 }
  2870.             }
  2871.         }
  2872.         $inv_head $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  2873.             'name' => 'warehouse_action_1'//for now for stock of goods
  2874.         ));
  2875.         return $this->render('ApplicationBundle:pages/inventory/input_forms:opening_item_assign.html.twig',
  2876.             array(
  2877.                 'page_title' => "Opening Items",
  2878.                 'inv_head' => $inv_head $inv_head->getData() : '',
  2879.                 'products' => $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  2880.                     'status' => GeneralConstant::ACTIVE//for now for stock of goods
  2881. //                    'opening_locked'=>0
  2882.                 )),
  2883.                 'warehouseList' => Inventory::WarehouseList($em),
  2884.                 'warehouseActionList' => $warehouse_action_list
  2885.             )
  2886.         );
  2887.     }
  2888.     public function CreateProductCategoryAction(Request $request)
  2889.     {
  2890.         if ($request->isMethod('POST')) {
  2891.             $cat_data Inventory::CreateCategory($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request), $request->request->get('cat_name'), $request->request->get('itemgroupId'), $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2892.             if ($cat_data['id'] != '')
  2893.                 return new JsonResponse(array("success" => true'cat_data' => $cat_data));
  2894.         }
  2895.         return new JsonResponse(array("success" => false,));
  2896. //        return $this->redirectToRoute("create_product");
  2897.     }
  2898.     public function CreateProductSubCategoryAction(Request $request)
  2899.     {
  2900.         if ($request->isMethod('POST')) {
  2901.             $spec_data Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
  2902.                 $this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
  2903.                 $request->request->get('level'0),
  2904.                 $request->request->get('parentId'0),
  2905.                 $request->request->get('itemgroupId'),
  2906.                 $request->request->get('categoryId'),
  2907.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2908.             if ($spec_data['id'] != '')
  2909.                 return new JsonResponse(array("success" => true'spec_data' => $spec_data));
  2910.         }
  2911.         return new JsonResponse(array("success" => false,));
  2912. //        return $this->redirectToRoute("create_product");
  2913.     }
  2914.     public function CreateProductBrandAction(Request $request)
  2915.     {
  2916.         if ($request->isMethod('POST')) {
  2917.             $data Inventory::CreateBrand($this->getDoctrine()->getManager(),
  2918.                 $this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
  2919.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  2920.             if ($data['id'] != '')
  2921.                 return new JsonResponse(array("success" => true'data' => $data));
  2922.         }
  2923.         return new JsonResponse(array("success" => false,));
  2924. //        return $this->redirectToRoute("create_product");
  2925.     }
  2926.     public function CreateIssueNoteAction(Request $request)
  2927.     {
  2928.         return $this->render('ApplicationBundle:pages/inventory/input_forms:issue_note.html.twig',
  2929.             array(
  2930.                 'page_title' => 'Issue Note'
  2931.             )
  2932.         );
  2933.     }
  2934.     public function ProcessDraftDeliveryReceiptAction(Request $request$id 0)
  2935.     {
  2936.         $em $this->getDoctrine()->getManager();
  2937.         $companyId $this->getLoggedUserCompanyId($request);
  2938.         $extId $id;
  2939.         $receiptId $id;
  2940.         $allowed 0;
  2941.         if ($request->isMethod('POST')) {
  2942.             $receiptId $request->request->get('deliveryReceiptId');
  2943.             $QD $this->getDoctrine()
  2944.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  2945.                 ->findOneBy(
  2946.                     array(
  2947.                         'deliveryReceiptId' => $receiptId
  2948.                     ),
  2949.                     array()
  2950.                 );
  2951.             $soId $QD->getSalesOrderId();
  2952.             $drData = [];
  2953.             $dr_item_data $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findBy(
  2954.                 array(
  2955.                     'deliveryReceiptId' => $receiptId,
  2956.                 )
  2957.             );
  2958.             foreach ($dr_item_data as $dr_item) {
  2959.                 $drData[] = array(
  2960.                     'soItemId' => $dr_item->getSalesorderItemId(),
  2961.                     'qty' => $dr_item->getQty()
  2962.                 );
  2963.             }
  2964. //            $drData=[
  2965. //                ['soItemId'=>9,'qty'=>9],
  2966. //                ['soItemId'=>9,'qty'=>9],
  2967. //                ['soItemId'=>9,'qty'=>9],
  2968. //            ];
  2969.             $toGetSoItemsId = [];
  2970.             $toGetDoItemsId = [];
  2971.             $drDataBySoItemId = [];
  2972.             $drDataByDoItemId = [];
  2973.             $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(array(
  2974.                 'salesOrderId' => $soId   //$id is soId
  2975.             ));
  2976.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  2977.                 foreach ($drData as $pp) {
  2978.                     $toGetSoItemsId[] = $pp['soItemId'];
  2979.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  2980.                 }
  2981.             } else {
  2982.                 foreach ($drData as $pp) {
  2983.                     $toGetDoItemsId[] = $pp['soItemId'];
  2984.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  2985.                 }
  2986.                 $do_item_data $em->getRepository('ApplicationBundle:DeliveryOrderItem')->findBy(
  2987.                     array(
  2988.                         'salesorderId' => $id,
  2989.                         'id' => $toGetDoItemsId
  2990.                     )
  2991.                 );
  2992.                 foreach ($do_item_data as $dd) {
  2993.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  2994.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  2995.                 }
  2996. //                $do_item_data = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
  2997. //                    array(
  2998. ////                'salesOrderId'=>$post_data->get('soId', null),
  2999. //                        'id' => $post_data->get('do_details_id')[$key]
  3000. //                    )
  3001. //                );
  3002.             }
  3003.             $so_item_data $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
  3004.                 array(
  3005.                     'salesOrderId' => $soId,
  3006.                     'id' => $toGetSoItemsId
  3007.                 )
  3008.             );
  3009.             $prev_so_amount $so->getSoAmount();
  3010.             $total_discounted_amount 0;
  3011.             $total_product_amount 0;
  3012.             $total_discount 0;
  3013.             $total_special_discount $so->getSpecialDiscountAmount();
  3014.             $total_special_discount_rate $so->getSpecialDiscountRate();
  3015.             foreach ($so_item_data as $item) {
  3016.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  3017.                 $price $item->getPrice();
  3018.                 $amount $qty $price;
  3019.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  3020.                 $discountedAmount $amount $discountAmount;
  3021.                 $total_discounted_amount += $discountedAmount;
  3022.                 $total_discount += $discountAmount;
  3023.                 $total_product_amount += $amount;
  3024.             }
  3025.             $aitRate $so->getAitRate();
  3026.             $vatRate $so->getVatRate();
  3027.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  3028.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  3029. //        $so->setVatRate($post->get('vat_rate', null));
  3030.             $vatAmount $total_discounted_amount * ($vatRate 100);
  3031.             $aitAmount $total_discounted_amount * ($aitRate 100);
  3032.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  3033.             //now get client
  3034.             $client $em->getRepository('ApplicationBundle:AccClients')->findOneBy(array(
  3035.                 'clientId' => $so->getClientId(),
  3036.             ));
  3037.             if ($client->getCreditLimitEnabled() != 1) {
  3038.                 $allowed 1;
  3039.             } else {
  3040.                 $creditLimit $client->getCreditLimit();
  3041.                 $due $client->getClientDue();
  3042.                 if ($creditLimit >= ($due $total_sales_amount))
  3043.                     $allowed 1;
  3044.             }
  3045.             //now package data
  3046.             if ($allowed == 0) {
  3047.                 return new JsonResponse(array(
  3048.                     'success' => false,
  3049. //                        'documentHash' => $order->getDocumentHash(),
  3050.                     'documentId' => $receiptId,
  3051.                     'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3052.                     'viewUrl' => '',
  3053.                 ));
  3054.             }
  3055.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3056.             $dochash $request->request->get('docHash'); //change
  3057.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3058.             $approveRole 1;  //created
  3059.             $approveHash $request->request->get('approvalHash');
  3060.             $receiptId $request->request->get('deliveryReceiptId');
  3061.             $sig DocValidation::isSignatureOk($em$loginId$approveHash);
  3062. //            $this->addFlash(
  3063. //                'success',
  3064. //                'New Transaction Added.'
  3065. //            );
  3066.             $success $sig == false true;
  3067.             if ($success == true) {
  3068.                 $QD $this->getDoctrine()
  3069.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3070.                     ->findOneBy(
  3071.                         array(
  3072.                             'deliveryReceiptId' => $receiptId
  3073.                         ),
  3074.                         array()
  3075.                     );
  3076.                 $draftFlag $QD->getDraftFlag();
  3077.                 if ($draftFlag == 1) {
  3078.                     //now add Approval info
  3079.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3080.                     $approveRole 1;  //created
  3081.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3082.                         $receiptId,
  3083.                         $loginId,
  3084.                         $approveRole,
  3085.                         $request->request->get('approvalHash'));
  3086.                     $options = array(
  3087.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3088.                         'notification_server' => $this->container->getParameter('notification_server'),
  3089.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3090.                         'url' => $this->generateUrl(
  3091.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3092.                             ['entity_view_route_path_name']
  3093.                         )
  3094.                     );
  3095.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3096.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3097.                         $receiptId,
  3098.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3099.                     );
  3100.                     $QD->setDraftFlag(0);
  3101.                     $em->flush();
  3102.                 }
  3103.                 $url $this->generateUrl(
  3104.                     'view_delivery_receipt'
  3105.                 );
  3106.                 if ($request->request->has('returnJson')) {
  3107. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  3108. //                        array(
  3109. //                            'salesOrderId' => $orderId, ///material
  3110. //
  3111. //                        )
  3112. //                    );
  3113.                     return new JsonResponse(array(
  3114.                         'success' => true,
  3115. //                        'documentHash' => $order->getDocumentHash(),
  3116.                         'documentId' => $receiptId,
  3117.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3118.                         'viewUrl' => $url "/" $receiptId,
  3119.                     ));
  3120.                 } else {
  3121.                     $this->addFlash(
  3122.                         'success',
  3123.                         'Action Successful'
  3124.                     );
  3125.                     return $this->redirect($url "/" $receiptId);
  3126.                 }
  3127.             }
  3128.         }
  3129.         return new JsonResponse(array(
  3130.             'success' => false,
  3131. //                        'documentHash' => $order->getDocumentHash(),
  3132.             'documentId' => $receiptId,
  3133.             'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3134.             'viewUrl' => '',
  3135.         ));
  3136.     }
  3137.     public function CreateDeliveryReceiptAction(Request $request$id 0)
  3138.     {
  3139.         $em $this->getDoctrine()->getManager();
  3140.         $companyId $this->getLoggedUserCompanyId($request);
  3141.         $userBranchIdList $request->getSession()->get('branchIdList');
  3142.         if ($userBranchIdList == null$userBranchIdList = [];
  3143.         $userBranchId $request->getSession()->get('branchId');
  3144.         $extId $id;
  3145.         $skipInventoryHit null;
  3146.         if ($request->query->has('skipInventoryHit'))
  3147.             $skipInventoryHit $request->query->get('skipInventoryHit');
  3148.         if ($request->isMethod('POST')) {
  3149.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  3150.             $dochash $request->request->get('docHash'); //change
  3151.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3152.             $approveRole 1;  //created
  3153.             $approveHash $request->request->get('approvalHash');
  3154.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3155.                 $loginId$approveRole$approveHash$request->request->get('drId'))
  3156.             ) {
  3157.                 if ($request->request->has('returnJson')) {
  3158.                     return new JsonResponse(array(
  3159.                         'success' => false,
  3160. //                        'documentHash' => 0,
  3161.                         'documentId' => 0,
  3162.                         'documentIdPadded' => str_pad(08'0'STR_PAD_LEFT),
  3163. //                        'documentDate' => '',
  3164. //                        'billIds' => [],
  3165. //                        'drIds' => [],
  3166. //                        'pmntTransIds' => [],
  3167.                         'viewUrl' => '',
  3168. //                        'skipApprovalAction' => $request->request->has('skipApprovalAction')?$request->request->get('skipApprovalAction'):0,
  3169. //                        'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  3170. //                        'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  3171. //                        'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  3172. //                        'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  3173.                     ));
  3174.                 } else
  3175.                     $this->addFlash(
  3176.                         'error',
  3177.                         'Sorry Could not insert Data.'
  3178.                     );
  3179.             } else {
  3180.                 $receiptId SalesOrderM::CreateNewDeliveryReceipt($this->getDoctrine()->getManager(), $request->request$skipInventoryHit,
  3181.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3182.                     $this->getLoggedUserCompanyId($request));
  3183.                 $draftFlag $request->request->has('draftFlag') ? $request->request->get('draftFlag') : 0;
  3184.                 if ($draftFlag == 0) {
  3185.                     //now add Approval info
  3186.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3187.                     $approveRole 1;  //created
  3188.                     System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3189.                         $receiptId,
  3190.                         $loginId,
  3191.                         $approveRole,
  3192.                         $request->request->get('approvalHash'));
  3193.                     $options = array(
  3194.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3195.                         'notification_server' => $this->container->getParameter('notification_server'),
  3196.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3197.                         'url' => $this->generateUrl(
  3198.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  3199.                             ['entity_view_route_path_name']
  3200.                         )
  3201.                     );
  3202.                     System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3203.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  3204.                         $receiptId,
  3205.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3206.                     );
  3207.                 }
  3208.                 $url $this->generateUrl(
  3209.                     'view_delivery_receipt'
  3210.                 );
  3211.                 if ($request->request->has('returnJson')) {
  3212. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  3213. //                        array(
  3214. //                            'salesOrderId' => $orderId, ///material
  3215. //
  3216. //                        )
  3217. //                    );
  3218.                     return new JsonResponse(array(
  3219.                         'success' => true,
  3220. //                        'documentHash' => $order->getDocumentHash(),
  3221.                         'documentId' => $receiptId,
  3222.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  3223.                         'viewUrl' => $url "/" $receiptId,
  3224.                     ));
  3225.                 } else {
  3226.                     $this->addFlash(
  3227.                         'success',
  3228.                         'New Delivery Receipt Created'
  3229.                     );
  3230.                     return $this->redirect($url "/" $receiptId);
  3231.                 }
  3232.             }
  3233.         }
  3234.         $debugData = [];
  3235. //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  3236. //            array(
  3237. //                'deliveryReceiptId'=>$dr_id
  3238. //            )
  3239. //        );
  3240.         $new_swld = new \DateTime('2017-07-09');
  3241. //        if ($entry->getWarranty() > 0)
  3242. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  3243.         $debugData[] = $new_swld->format('Y-m-d');
  3244.         $debugData[] = $new_swld;
  3245. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  3246.         $debugData[] = '+' '1' ' month';
  3247.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  3248.         $warehouseIds = [];
  3249.         foreach ($branchList as $br) {
  3250.             $warehouseIds[] = $br['warehouseId'];
  3251.         }
  3252.         $extDocData = [];
  3253.         $extDocDataDetails = [];
  3254.         if ($extId == 0) {
  3255.         } else {
  3256.             $extDoc $em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  3257.                 array(
  3258.                     'deliveryReceiptId' => $extId///material
  3259.                 )
  3260.             );
  3261.             //now if its not editable, redirect to view
  3262.             if ($extDoc) {
  3263.                 if ($extDoc->getEditFlag() != && $extDoc->getDraftFlag() != 1) {
  3264.                     $url $this->generateUrl(
  3265.                         'view_delivery_receipt'
  3266.                     );
  3267.                     return $this->redirect($url "/" $extId);
  3268.                 } else {
  3269.                     $extDocData $extDoc;
  3270.                     $extDocDataDetails $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findOneBy(
  3271.                         array(
  3272.                             'deliveryReceiptId' => $extId///material
  3273.                         )
  3274.                     );
  3275.                 }
  3276.             } else {
  3277.             }
  3278.         }
  3279.         return $this->render('ApplicationBundle:pages/inventory/input_forms:deliveryReceipt.html.twig',
  3280.             array(
  3281.                 'page_title' => 'New Delivery Receipt',
  3282.                 'extDocDataDetails' => $extDocDataDetails,
  3283.                 'extDocData' => $extDocData,
  3284.                 'extData' => $extDocData,
  3285.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  3286.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($em),
  3287.                 'ClientList' => SalesOrderM::GetClientList($em),
  3288.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  3289.                 'salesOrders' => SalesOrderM::SalesOrderListPendingDelivery($em$warehouseIds),
  3290.                 'salesOrdersArray' => SalesOrderM::SalesOrderListPendingDeliveryArray($em$warehouseIds),
  3291.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  3292.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  3293.                 'debugData' => $debugData,
  3294.             )
  3295.         );
  3296.     }
  3297.     public function CreateServiceChallanAction(Request $request)
  3298.     {
  3299.         $em $this->getDoctrine()->getManager();
  3300.         if ($request->isMethod('POST')) {
  3301.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //change
  3302.             $dochash $request->request->get('docHash'); //change
  3303.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3304.             $approveRole $request->request->get('approvalRole');
  3305.             $approveHash $request->request->get('approvalHash');
  3306.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  3307.                 $loginId$approveRole$approveHash)
  3308.             ) {
  3309.                 $this->addFlash(
  3310.                     'error',
  3311.                     'Sorry Could not insert Data.'
  3312.                 );
  3313.             } else {
  3314.                 $receiptId SalesOrderM::CreateNewServiceChallan($this->getDoctrine()->getManager(), $request->request,
  3315.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3316.                     $this->getLoggedUserCompanyId($request));
  3317.                 //now add Approval info
  3318.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3319. //                $approveRole = 1;  //created
  3320.                 $options = array(
  3321.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3322.                     'notification_server' => $this->container->getParameter('notification_server'),
  3323.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3324.                     'url' => $this->generateUrl(
  3325.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceChallan']]
  3326.                         ['entity_view_route_path_name']
  3327.                     )
  3328.                 );
  3329.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  3330.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3331.                     $receiptId,
  3332.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3333.                 );
  3334.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  3335.                     $receiptId,
  3336.                     $loginId,
  3337.                     $approveRole,
  3338.                     $request->request->get('approvalHash'));
  3339.                 $this->addFlash(
  3340.                     'success',
  3341.                     'New Service Challan Created'
  3342.                 );
  3343.                 $url $this->generateUrl(
  3344.                     'view_service_challan'
  3345.                 );
  3346.                 return $this->redirect($url "/" $receiptId);
  3347.             }
  3348.         }
  3349.         return $this->render('ApplicationBundle:pages/inventory/input_forms:create_service_challan.html.twig',
  3350.             array(
  3351.                 'page_title' => 'New Service Challan',
  3352.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3353.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3354.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3355.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  3356.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  3357.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  3358.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  3359.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  3360.                 'serviceList' => Inventory::ServiceList($em$this->getLoggedUserCompanyId($request))
  3361.             )
  3362.         );
  3363.     }
  3364.     public function GetItemListForDrAction(Request $request)
  3365.     {
  3366.         $em $this->getDoctrine()->getManager();
  3367.         $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3368.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3369.         if ($request->isMethod('POST')) {
  3370.             $em $this->getDoctrine();
  3371.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3372.             );
  3373.             $Content = [];
  3374.             $Transport_data = [];
  3375.             $Lul_data = [];
  3376.             if ($request->request->get('doId') != '')
  3377.                 $find_array['deliveryOrderId'] = $request->request->get('doId');
  3378. //            if($request->request->get('warehouseId')!='')
  3379. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3380.             $QD $this->getDoctrine()
  3381.                 ->getRepository('ApplicationBundle:DeliveryOrderItem')
  3382.                 ->findBy(
  3383.                     $find_array,
  3384.                     array()
  3385.                 );
  3386. //            if($request->request->get('wareHouseId')!='')
  3387.             $DO $this->getDoctrine()
  3388.                 ->getRepository('ApplicationBundle:DeliveryOrder')
  3389.                 ->findOneBy(
  3390.                     $find_array,
  3391.                     array()
  3392.                 );
  3393.             $sendData = array(
  3394. //                'salesType'=>$SO->getSalesType(),
  3395. //                'packageData'=>[],
  3396.                 'productList' => [],
  3397. //                'productListByPackage'=>[],
  3398.             );
  3399.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3400.             $pckg_item_cross_match_data = [];
  3401.             $unitList Inventory::UnitTypeList($em);
  3402.             $colorList Inventory::GetColorList($em);
  3403.             foreach ($QD as $product) {
  3404. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3405.                 if (($product->getBalance()) <= 0)
  3406.                     continue;
  3407.                 $fdm $product->getProductFdm();
  3408.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3409.                 $find_query = array();
  3410.                 $soItem $this->getDoctrine()
  3411.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3412.                     ->findOneBy(
  3413.                         array(
  3414.                             'id' => $product->getSalesorderItemId()
  3415.                         )
  3416.                     );
  3417.                 if (!$soItem)
  3418.                     continue;
  3419. //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3420. //                $soBalance = $soItem->getBalance();
  3421.                 $soBalance $soItem->getQty();
  3422. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3423. //                $doBalance = $product->getBalance();
  3424.                 $doBalance $product->getQty();
  3425.                 //now check if any so ir do item id there that is at
  3426.                 //least pending
  3427.                 $approvalPendingDrs $this->getDoctrine()
  3428.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3429.                     ->findBy(
  3430.                         array(
  3431.                             'deliveryOrderId' => $DO->getDeliveryOrderId(),
  3432.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3433.                         )
  3434.                     );
  3435.                 foreach ($approvalPendingDrs as $appPendDr) {
  3436.                     $appPendDrItem $this->getDoctrine()
  3437.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3438.                         ->findOneBy(
  3439.                             array(
  3440.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3441.                                 'salesorderItemId' => $product->getSalesorderItemId()
  3442.                             )
  3443.                         );
  3444.                     if ($appPendDrItem) {
  3445.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3446.                             $soBalance $soBalance $appPendDrItem->getQty();
  3447.                             $doBalance $doBalance $appPendDrItem->getQty();
  3448.                         }
  3449.                     }
  3450.                 }
  3451.                 $colorId $product->getColorId();
  3452.                 $size $product->getSizeId();
  3453. //                $find_query['colorId']=
  3454.                 if ($productData['productId'] != 0) {
  3455.                     $find_query['productId'] = $productData['productId'];
  3456.                     if ($colorId == '' || $colorId == || $colorId == null)
  3457.                         $colorId $productData['defaultColorId'];
  3458.                     if ($size == '' || $size == || $size == null)
  3459.                         $size $productData['defaultSize'];
  3460.                     $find_query['productId'] = $productData['productId'];
  3461.                 } else {
  3462.                     if ($productData['igId'] != 0) {
  3463.                         $find_query['igId'] = $productData['igId'];
  3464.                     }
  3465.                     if ($productData['categoryId'] != 0) {
  3466.                         $find_query['categoryId'] = $productData['categoryId'];
  3467.                     }
  3468.                     if ($productData['subCategoryId'] != 0) {
  3469.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3470.                     }
  3471.                     if ($productData['brandId'] != 0) {
  3472.                         $find_query['brandId'] = $productData['brandId'];
  3473.                     }
  3474.                 }
  3475.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3476.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3477.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3478. //                    $find_query['color'] = $colorId;
  3479.                 } else
  3480.                     $find_query['color'] = $colorId;
  3481.                 if ($size == '' || $size == || $size == null) {
  3482. //                    $find_query['size'] = $size;
  3483.                 } else
  3484.                     $find_query['size'] = 0;
  3485.                 $inventory_by_warehouse_list $this->getDoctrine()
  3486.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3487.                     ->findBy(
  3488.                         $find_query,
  3489.                         array()
  3490.                     );
  3491.                 $new_pid $productData['productId'];
  3492.                 $p_data = array(
  3493.                     'details_id' => $product->getId(),
  3494. //                        'productId'=>$new_pid,
  3495.                     'productIdList' => [],
  3496.                     'multList' => [],
  3497.                     'drItemIds' => [],
  3498.                     'drItemQty' => [],
  3499.                     'drItemCodeIds' => [],
  3500.                     'drItemCartonIds' => [],
  3501.                     'colorIds' => [],
  3502.                     'colorNames' => [],
  3503.                     'sizeIds' => [],
  3504.                     'productNameList' => [],
  3505.                     'availableInventoryList' => [],
  3506.                     'warehouseActionId' => [],
  3507.                     'warehouseActionName' => [],
  3508.                     'availableBarcodes' => [],
  3509.                     'availableBarcodesStr' => [],
  3510. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3511. //                        'available_inventory'=>0,
  3512. //                        'package_id'=>$product->getPackageId(),
  3513.                     'qty' => $product->getQty(),
  3514.                     'delivered' => $product->getDelivered(),
  3515. //                    'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
  3516.                     'deliverable' => min($soBalance$doBalance),
  3517. //                    'balance' => $product->getBalance(),
  3518.                     'balance' => min($soBalance$doBalance),
  3519.                     'productNameFdm' => $product->getProductNameFdm(),
  3520.                     'productFdm' => $product->getProductFdm(),
  3521. //                        'delivered'=>$product->getDelivered(),
  3522.                 );
  3523.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3524.                     if ($inventory_by_warehouse->getQty() <= 0)
  3525.                         continue;
  3526.                     $unitType $product->getUnitTypeId();
  3527.                     $mult_unit 1;
  3528.                     if ($drId != 0) {
  3529.                         $drItem $this->getDoctrine()
  3530.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3531.                             ->findOneBy(
  3532.                                 array(
  3533.                                     'deliveryReceiptId' => $drId,
  3534.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3535.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3536.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3537.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3538.                                 )
  3539.                             );
  3540.                         if ($drItem) {
  3541.                             $p_data['drItemIds'][] = $drItem->getId();
  3542.                             $p_data['drItemQty'][] = $drItem->getQty();
  3543.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3544.                             if ($codes == null)
  3545.                                 $codes = [];
  3546.                             $p_data['drItemCodeIds'][] = $codes;
  3547.                             $codes json_decode($drItem->getCartonIds(), true);
  3548.                             if ($codes == null)
  3549.                                 $codes = [];
  3550.                             $p_data['drItemCartonIds'][] = $codes;
  3551.                         } else {
  3552.                             $p_data['drItemIds'][] = 0;
  3553.                             $p_data['drItemQty'][] = 0;
  3554.                             $p_data['drItemCodeIds'][] = 0;
  3555.                             $p_data['drItemCartonIds'][] = 0;
  3556.                         }
  3557.                     } else {
  3558.                         $p_data['drItemIds'][] = 0;
  3559.                         $p_data['drItemQty'][] = 0;
  3560.                         $p_data['drItemCodeIds'][] = 0;
  3561.                         $p_data['drItemCartonIds'][] = 0;
  3562.                     }
  3563.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3564.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3565.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3566.                         }
  3567.                     };
  3568.                     if ($mult_unit == 0)
  3569.                         $mult_unit 1;
  3570.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3571.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3572.                     $p_data['multList'][] = $mult_unit;
  3573.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3574.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3575.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3576.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3577.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3578. //                        $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
  3579.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3580.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3581.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3582.                 }
  3583.                 $sendData['productList'][] = $p_data;
  3584.             }
  3585.             //now package data
  3586.             if ($sendData) {
  3587.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3588.             }
  3589.             return new JsonResponse(array("success" => false));
  3590.         }
  3591.         return new JsonResponse(array("success" => false));
  3592.     }
  3593.     public function GetItemListForDrBySoAction(Request $request)
  3594.     {
  3595.         $em $this->getDoctrine()->getManager();
  3596.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3597.         if ($request->isMethod('POST')) {
  3598.             $em $this->getDoctrine();
  3599.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3600. //                'type'=>1//product only
  3601.             );
  3602.             $find_item_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3603.                 'type' => 1//product only
  3604.             );
  3605.             $Content = [];
  3606.             $Transport_data = [];
  3607.             $Lul_data = [];
  3608.             $drId $request->request->has('drId') ? $request->request->get('drId') : 0;
  3609.             if ($request->request->get('soId') != '') {
  3610.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3611.                 $find_item_array['salesOrderId'] = $request->request->get('soId');
  3612.             }
  3613. //            if($request->request->get('warehouseId')!='')
  3614. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3615.             $QD $this->getDoctrine()
  3616.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  3617.                 ->findBy(
  3618.                     $find_item_array,
  3619.                     array()
  3620.                 );
  3621. //            if($request->request->get('wareHouseId')!='')
  3622.             $DO $this->getDoctrine()
  3623.                 ->getRepository('ApplicationBundle:SalesOrder')
  3624.                 ->findOneBy(
  3625.                     $find_array,
  3626.                     array()
  3627.                 );
  3628.             $sendData = array(
  3629. //                'salesType'=>$SO->getSalesType(),
  3630. //                'packageData'=>[],
  3631.                 'productList' => [],
  3632. //                'productListByPackage'=>[],
  3633.             );
  3634.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3635.             $pckg_item_cross_match_data = [];
  3636.             $unitList Inventory::UnitTypeList($em);
  3637.             $colorList Inventory::GetColorList($em);
  3638.             foreach ($QD as $product) {
  3639.                 if (($product->getBalance() - $product->getTransitQty()) <= 0)
  3640.                     continue;
  3641.                 //                $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
  3642. //                $soBalance = $soItem->getBalance();
  3643.                 $soBalance $product->getQty();
  3644. //                $doBalance=$product->getBalance() - $product->getTransitQty();
  3645. //                $doBalance = $product->getBalance();
  3646. //                $doBalance = 0;
  3647.                 //now check if any so ir do item id there that is at
  3648.                 //least pending
  3649.                 $approvalPendingDrs $this->getDoctrine()
  3650.                     ->getRepository('ApplicationBundle:DeliveryReceipt')
  3651.                     ->findBy(
  3652.                         array(
  3653.                             'salesOrderId' => $DO->getSalesOrderId(),
  3654.                             'approved' => [2GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  3655.                         )
  3656.                     );
  3657.                 foreach ($approvalPendingDrs as $appPendDr) {
  3658.                     $appPendDrItem $this->getDoctrine()
  3659.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3660.                         ->findOneBy(
  3661.                             array(
  3662.                                 'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
  3663. //                                'salesorderItemId' => $product->getId(),
  3664.                                 'salesorderItemId' => $product->getId()
  3665.                             )
  3666.                         );
  3667.                     if ($appPendDrItem) {
  3668.                         if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
  3669.                             $soBalance $soBalance $appPendDrItem->getQty();
  3670.                         }
  3671. //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  3672.                     }
  3673.                 }
  3674.                 $fdm $product->getProductFdm();
  3675.                 $productData Inventory::GetProductDataFromFdm($em$fdm$DO->getCompanyId(), 0);
  3676.                 $find_query = array();
  3677.                 $colorId $product->getColorId();
  3678.                 $size $product->getSizeId();
  3679. //                $find_query['colorId']=
  3680.                 if ($productData['productId'] != 0) {
  3681.                     $find_query['productId'] = $productData['productId'];
  3682.                     if ($colorId == '' || $colorId == || $colorId == null)
  3683.                         $colorId $productData['defaultColorId'];
  3684.                     if ($size == '' || $size == || $size == null)
  3685.                         $size $productData['defaultSize'];
  3686.                 } else {
  3687.                     if ($productData['igId'] != 0) {
  3688.                         $find_query['igId'] = $productData['igId'];
  3689.                     }
  3690.                     if ($productData['categoryId'] != 0) {
  3691.                         $find_query['categoryId'] = $productData['categoryId'];
  3692.                     }
  3693.                     if ($productData['subCategoryId'] != 0) {
  3694.                         $find_query['subCategoryId'] = $productData['subCategoryId'];
  3695.                     }
  3696.                     if ($productData['brandId'] != 0) {
  3697.                         $find_query['brandId'] = $productData['brandId'];
  3698.                     }
  3699.                 }
  3700.                 $find_query['warehouseId'] = $request->request->get('warehouseId');
  3701.                 $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3702.                 if ($colorId == '' || $colorId == || $colorId == null) {
  3703. //                    $find_query['color'] = $colorId;
  3704.                 } else
  3705.                     $find_query['color'] = $colorId;
  3706.                 if ($size == '' || $size == || $size == null) {
  3707. //                    $find_query['size'] = $size;
  3708.                 } else
  3709.                     $find_query['size'] = 0;
  3710.                 $inventory_by_warehouse_list $this->getDoctrine()
  3711.                     ->getRepository('ApplicationBundle:InventoryStorage')
  3712.                     ->findBy(
  3713.                         $find_query,
  3714.                         array()
  3715.                     );
  3716.                 $new_pid $productData['productId'];
  3717.                 $unitType $product->getUnitTypeId();
  3718.                 $p_data = array(
  3719.                     'details_id' => $product->getId(),
  3720.                     'unitType' => $unitType,
  3721.                     'productIdList' => [],
  3722.                     'multList' => [],
  3723.                     'drItemIds' => [],
  3724.                     'drItemQty' => [],
  3725.                     'drItemCodeIds' => [],
  3726.                     'drItemCartonIds' => [],
  3727.                     'colorIds' => [],
  3728.                     'colorNames' => [],
  3729.                     'sizeIds' => [],
  3730.                     'productNameList' => [],
  3731.                     'availableInventoryList' => [],
  3732.                     'warehouseActionId' => [],
  3733.                     'warehouseActionName' => [],
  3734.                     'availableBarcodes' => [],
  3735.                     'availableBarcodesStr' => [],
  3736. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3737. //                        'available_inventory'=>0,
  3738. //                        'package_id'=>$product->getPackageId(),
  3739.                     'qty' => $product->getQty(),
  3740.                     'delivered' => $product->getDelivered(),
  3741. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3742. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3743.                     'deliverable' => $soBalance,
  3744. //                    'deliverable' => $product->getBalance(),
  3745.                     'balance' => $soBalance,
  3746. //                    'balance' => $product->getBalance(),
  3747.                     'productNameFdm' => $product->getProductNameFdm(),
  3748.                     'productFdm' => $product->getProductFdm(),
  3749. //                        'delivered'=>$product->getDelivered(),
  3750.                 );
  3751.                 foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
  3752.                     if ($inventory_by_warehouse->getQty() <= 0)
  3753.                         continue;
  3754.                     $mult_unit 1;
  3755.                     if ($drId != 0) {
  3756.                         $drItem $this->getDoctrine()
  3757.                             ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3758.                             ->findOneBy(
  3759.                                 array(
  3760.                                     'deliveryReceiptId' => $drId,
  3761.                                     'productId' => $inventory_by_warehouse->getProductId(),
  3762.                                     'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
  3763.                                     'colorId' => $inventory_by_warehouse->getColor() == ? [0null''] : $inventory_by_warehouse->getColor(),
  3764.                                     'sizeId' => $inventory_by_warehouse->getSize() == ? [0null''] : $inventory_by_warehouse->getSize(),
  3765.                                 )
  3766.                             );
  3767.                         if ($drItem) {
  3768.                             $p_data['drItemIds'][] = $drItem->getId();
  3769.                             $p_data['drItemQty'][] = $drItem->getQty();
  3770.                             $codes json_decode($drItem->getProductByCodeIds(), true);
  3771.                             if ($codes == null)
  3772.                                 $codes = [];
  3773.                             $p_data['drItemCodeIds'][] = $codes;
  3774.                             $codes json_decode($drItem->getCartonIds(), true);
  3775.                             if ($codes == null)
  3776.                                 $codes = [];
  3777.                             $p_data['drItemCartonIds'][] = $codes;
  3778.                         } else {
  3779.                             $p_data['drItemIds'][] = 0;
  3780.                             $p_data['drItemQty'][] = 0;
  3781.                             $p_data['drItemCodeIds'][] = 0;
  3782.                             $p_data['drItemCartonIds'][] = 0;
  3783.                         }
  3784.                     } else {
  3785.                         $p_data['drItemIds'][] = 0;
  3786.                         $p_data['drItemQty'][] = 0;
  3787.                         $p_data['drItemCodeIds'][] = 0;
  3788.                         $p_data['drItemCartonIds'][] = 0;
  3789.                     }
  3790.                     if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
  3791.                         if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
  3792.                             $mult_unit $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
  3793.                         }
  3794.                     };
  3795.                     if ($mult_unit == 0)
  3796.                         $mult_unit 1;
  3797.                     $inv_product_id $inventory_by_warehouse->getProductId();
  3798.                     $p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
  3799.                     $p_data['multList'][] = $mult_unit;
  3800.                     $p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
  3801.                     $p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
  3802.                     $p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
  3803.                     $p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
  3804.                     $p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
  3805.                     $p_data['colorIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getColor() : 0;
  3806.                     $p_data['sizeIds'][] = $inventory_by_warehouse $inventory_by_warehouse->getSize() : 0;
  3807.                     $p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
  3808.                 }
  3809.                 $sendData['productList'][] = $p_data;
  3810.             }
  3811.             //now package data
  3812.             if ($sendData) {
  3813.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3814.             }
  3815.             return new JsonResponse(array("success" => false));
  3816.         }
  3817.         return new JsonResponse(array("success" => false));
  3818.     }
  3819.     public function GetItemListForStockReqBySoAction(Request $request)
  3820.     {
  3821.         $em $this->getDoctrine()->getManager();
  3822.         if ($request->isMethod('POST')) {
  3823.             $em $this->getDoctrine();
  3824.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3825.             );
  3826.             $Content = [];
  3827.             $Transport_data = [];
  3828.             $Lul_data = [];
  3829.             $find_array['serviceId'] = [0null];
  3830.             $sendData = array(
  3831. //                'salesType'=>$SO->getSalesType(),
  3832. //                'packageData'=>[],
  3833.                 'productList' => [],
  3834. //                'productListByPackage'=>[],
  3835.             );
  3836.             if ($request->request->get('soId') != '') {
  3837.                 $find_array['salesOrderId'] = $request->request->get('soId');
  3838. //            if($request->request->get('warehouseId')!='')
  3839. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3840.                 $QD $this->getDoctrine()
  3841.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  3842.                     ->findBy(
  3843.                         $find_array,
  3844.                         array()
  3845.                     );
  3846. //            if($request->request->get('wareHouseId')!='')
  3847. //            $DO = $this->getDoctrine()
  3848. //                ->getRepository('ApplicationBundle:SalesOrder')
  3849. //                ->findOneBy(
  3850. //                    $find_array,
  3851. //                    array()
  3852. //                );
  3853.                 $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3854.                 $pckg_item_cross_match_data = [];
  3855.                 $unitList Inventory::UnitTypeList($em);
  3856.                 foreach ($QD as $product) {
  3857. //                if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
  3858. //                    continue;
  3859.                     $fdm $product->getProductFdm();
  3860.                     $unitType $product->getUnitTypeId();
  3861.                     $p_data = array(
  3862.                         'details_id' => $product->getId(),
  3863.                         'unitType' => $unitType,
  3864.                         'productIdList' => [],
  3865.                         'multList' => [],
  3866.                         'productNameList' => [],
  3867.                         'availableInventoryList' => [],
  3868.                         'warehouseActionId' => [],
  3869.                         'warehouseActionName' => [],
  3870.                         'availableBarcodes' => [],
  3871.                         'availableBarcodesStr' => [],
  3872. //                        'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
  3873. //                        'available_inventory'=>0,
  3874. //                        'package_id'=>$product->getPackageId(),
  3875.                         'qty' => $product->getQty(),
  3876.                         'delivered' => $product->getDelivered(),
  3877. //                    'deliverable' => $product->getBalance() - $product->getTransitQty(),
  3878. //                    'balance' => $product->getBalance() - $product->getTransitQty(),
  3879.                         'deliverable' => $product->getBalance(),
  3880.                         'balance' => $product->getBalance(),
  3881.                         'productNameFdm' => $product->getProductNameFdm(),
  3882.                         'productFdm' => $product->getProductFdm(),
  3883. //                        'delivered'=>$product->getDelivered(),
  3884.                     );
  3885.                     $sendData['productList'][] = $p_data;
  3886.                 }
  3887.             }
  3888.             //now package data
  3889.             if ($sendData) {
  3890.                 return new JsonResponse(array("success" => true"content" => $sendData));
  3891.             }
  3892.             return new JsonResponse(array("success" => false));
  3893.         }
  3894.         return new JsonResponse(array("success" => false));
  3895.     }
  3896.     public function GetBarcodesListForStAction(Request $request)
  3897.     {
  3898.         $em $this->getDoctrine()->getManager();
  3899.         $sendData = [];
  3900.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  3901.         if ($request->isMethod('POST')) {
  3902.             $em $this->getDoctrine();
  3903.             $find_query = array();
  3904.             $find_query['warehouseId'] = $request->request->get('warehouseId');
  3905.             $find_query['actionTagId'] = $request->request->get('warehouseActionId');
  3906.             $find_query['productId'] = $request->request->get('productId');
  3907.             $find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
  3908.             $inventory_by_warehouse_list $this->getDoctrine()
  3909.                 ->getRepository('ApplicationBundle:InventoryStorage')
  3910.                 ->findBy(
  3911.                     $find_query,
  3912.                     array()
  3913.                 );
  3914.             $new_pid $request->request->get('productId');
  3915.             $p_data = array();
  3916.             //now get bacodes if available
  3917. //                    $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
  3918. //FROM product_by_code
  3919. //where company_id=" . $this->getLoggedUserCompanyId($request).
  3920. //                        " and product_id=".$inv_product_id.
  3921. //                        " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
  3922. //                        " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
  3923. //                        " GROUP BY product_by_code_id" ;
  3924.             $query "SELECT product_by_code_id, sales_code
  3925. FROM product_by_code
  3926. where company_id=" $this->getLoggedUserCompanyId($request) .
  3927.                 " and product_id=" $request->request->get('productId') .
  3928.                 " and warehouse_id=" $request->request->get('warehouseId') .
  3929.                 " and warehouse_action_id=" $request->request->get('warehouseActionId');
  3930.             $stmt $em->getConnection()->prepare($query);
  3931.             $stmt->execute();
  3932.             $results $stmt->fetchAll();
  3933.             $sales_code_list_str '';
  3934.             foreach ($results as $pika => $result) {
  3935.                 if ($pika != 0)
  3936.                     $sales_code_list_str .= ',';
  3937.                 $sales_code_list_str .= str_pad($result['sales_code'], 13'0'STR_PAD_LEFT);
  3938.             }
  3939.             if ($results) {
  3940.                 $p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3941.                     explode(','$sales_code_list_str) : [];
  3942.                 $p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
  3943.                     $sales_code_list_str "";
  3944. //
  3945.             } else {
  3946.                 $p_data['availableBarcodes'] = [];
  3947.                 $p_data['availableBarcodesStr'] = "";
  3948. //
  3949.             }
  3950.             $sendData $p_data;
  3951.         }
  3952.         //now package data
  3953.         if (!empty($sendData['availableBarcodes'])) {
  3954.             return new JsonResponse(array("success" => true"content" => $sendData));
  3955.         }
  3956.         return new JsonResponse(array("success" => false));
  3957.     }
  3958.     public function GetItemListForSalesReturnAction(Request $request)
  3959.     {
  3960.         if ($request->isMethod('POST')) {
  3961.             $em $this->getDoctrine();
  3962.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  3963.             );
  3964.             $Content = [];
  3965.             $Transport_data = [];
  3966.             $Lul_data = [];
  3967.             if ($request->request->get('drId') != '')
  3968.                 $find_array['deliveryReceiptId'] = $request->request->get('drId');
  3969. //            if($request->request->get('warehouseId')!='')
  3970. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  3971.             $QD $this->getDoctrine()
  3972.                 ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  3973.                 ->findBy(
  3974.                     $find_array,
  3975.                     array()
  3976.                 );
  3977. //            if($request->request->get('wareHouseId')!='')
  3978.             $DR $this->getDoctrine()
  3979.                 ->getRepository('ApplicationBundle:DeliveryReceipt')
  3980.                 ->findOneBy(
  3981.                     $find_array,
  3982.                     array()
  3983.                 );
  3984.             $sendData = array(
  3985.                 'productList' => [],
  3986.             );
  3987.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  3988.             $pckg_item_cross_match_data = [];
  3989.             $unitList Inventory::UnitTypeList($em);
  3990.             foreach ($QD as $product) {
  3991.                 if (($product->getQty()) <= 0)
  3992.                     continue;
  3993.                 $new_pid $product->getProductId();
  3994.                 $sales_code_range = [];
  3995.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  3996.                     $sales_code_range json_decode($product->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  3997.                 } else {
  3998.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  3999.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getSalesCodeRange());
  4000.                     $sales_code_range json_decode($json_without_bigintstrue);
  4001.                 }
  4002.                 $p_data = array(
  4003.                     'details_id' => $product->getId(),
  4004.                     'dr_id' => $product->getDeliveryReceiptId(),
  4005.                     'productId' => $new_pid,
  4006.                     'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
  4007.                     'qty' => $product->getQty(),
  4008.                     'delivered' => $product->getDelivered(),
  4009.                     'unitTypeId' => $product->getUnitTypeId(),
  4010.                     'deliverable' => $product->getDeliverable(),
  4011.                     'balance' => $product->getBalance(),
  4012.                     'salesCodeRangeStr' => $product->getSalesCodeRange(),
  4013.                     'salesCodeRange' => $sales_code_range,
  4014.                     'sales_codes' => $sales_code_range,
  4015.                     'sales_price' => $product->getPrice(),
  4016.                     'purchase_price' => $product->getCurrentPurchasePrice()
  4017. //                        'delivered'=>$product->getDelivered(),
  4018.                 );
  4019.                 $sendData['productList'][] = $p_data;
  4020.             }
  4021.             //now package data
  4022.             if ($sendData) {
  4023.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4024.             }
  4025.             return new JsonResponse(array("success" => false));
  4026.         }
  4027.         return new JsonResponse(array("success" => false));
  4028.     }
  4029.     public function GetItemListForIrrAction(Request $request)
  4030.     {
  4031.         if ($request->isMethod('POST')) {
  4032.             $em $this->getDoctrine();
  4033.             $find_array = array(//                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  4034.             );
  4035.             $Content = [];
  4036.             $Transport_data = [];
  4037.             $Lul_data = [];
  4038.             if ($request->request->get('srId') != '')
  4039.                 $find_array['salesReturnId'] = $request->request->get('srId');
  4040. //            if($request->request->get('warehouseId')!='')
  4041. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4042.             $QD $this->getDoctrine()
  4043.                 ->getRepository('ApplicationBundle:SalesReturnItem')
  4044.                 ->findBy(
  4045.                     $find_array,
  4046.                     array()
  4047.                 );
  4048. //            if($request->request->get('wareHouseId')!='')
  4049.             $sendData = array(
  4050.                 'productList' => [],
  4051.             );
  4052.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4053.             $pckg_item_cross_match_data = [];
  4054.             $unitList Inventory::UnitTypeList($em);
  4055.             foreach ($QD as $product) {
  4056.                 if (($product->getReceivedBalance()) <= && ($product->getReplacedBalance()) <= 0)
  4057.                     continue;
  4058.                 $DR_ITEM null;
  4059.                 $DR_TAGGED_CODES = [];
  4060.                 $DR_TAGGED_CODES_FOR_SELECTIZE = [];
  4061.                 $RESTRICT_RECEIVED_CODES_FLAG 0;
  4062.                 $sales_code_range = [];
  4063.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  4064.                     $sales_code_range json_decode($product->getReceivedCodeRange(), true512JSON_BIGINT_AS_STRING);
  4065.                 } else {
  4066.                     $max_int_length strlen((string)PHP_INT_MAX) - 1;
  4067.                     $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$product->getReceivedCodeRange());
  4068.                     $sales_code_range json_decode($json_without_bigintstrue);
  4069.                 }
  4070.                 $DR_TAGGED_CODES $sales_code_range;
  4071.                 if (!empty($DR_TAGGED_CODES)) {
  4072.                     $RESTRICT_RECEIVED_CODES_FLAG 1;
  4073.                     foreach ($DR_TAGGED_CODES as $DTC) {
  4074.                         $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4075.                             'value' => $DTC
  4076.                         );
  4077.                     }
  4078.                 }
  4079. //                if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
  4080. //
  4081. //                    $DR_ITEM = $this->getDoctrine()
  4082. //                        ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  4083. //                        ->findOneBy(
  4084. //                            array(
  4085. //                                'id' => $product->getTaggedDetailsId()
  4086. //                            ),
  4087. //                            array()
  4088. //                        );
  4089. //                    if ($DR_ITEM) {
  4090. //                        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  4091. //
  4092. //                            $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  4093. //                        } else {
  4094. //
  4095. //                            $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  4096. //                            $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
  4097. //                            $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
  4098. //                        }
  4099. //
  4100. //                        if ($DR_TAGGED_CODES == null)
  4101. //                            $DR_TAGGED_CODES = [];
  4102. //                        if (!empty($DR_TAGGED_CODES)) {
  4103. //                            $RESTRICT_RECEIVED_CODES_FLAG = 1;
  4104. //                            foreach ($DR_TAGGED_CODES as $DTC) {
  4105. //                                $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
  4106. //                                    'value' => $DTC
  4107. //                                );
  4108. //                            }
  4109. //                        }
  4110. //                    }
  4111. //                }
  4112.                 $p_data = array(
  4113.                     'details_id' => $product->getId(),
  4114.                     'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
  4115.                     'receivedDrTaggedCodesStr' => implode(','$DR_TAGGED_CODES),
  4116.                     'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
  4117.                     'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
  4118.                     'receivedProductId' => $product->getReceivedProductId(),
  4119.                     'receivedBalance' => $product->getReceivedBalance(),
  4120.                     'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
  4121.                     'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
  4122.                     'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
  4123.                     'replacedProductId' => $product->getReplacedProductId(),
  4124.                     'replacedBalance' => $product->getReplacedBalance(),
  4125.                     'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
  4126.                     'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
  4127.                     'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
  4128.                     'disposeBalance' => $product->getDisposeBalance(),
  4129.                     'unusedBalance' => $product->getUnusedBalance(),
  4130.                     'disposeTag' => $product->getDisposeTag(),
  4131.                     'unitTypeId' => $product->getUnitTypeId(),
  4132. //                        'delivered'=>$product->getDelivered(),
  4133.                 );
  4134.                 $sendData['productList'][] = $p_data;
  4135.             }
  4136.             //now package data
  4137.             if ($sendData) {
  4138.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4139.             }
  4140.             return new JsonResponse(array("success" => false));
  4141.         }
  4142.         return new JsonResponse(array("success" => false));
  4143.     }
  4144.     public function LabelFormatAction(Request $request$id 0)
  4145.     {
  4146.         $data = array(
  4147.             'formatId' => '',
  4148.             'formatCode' => '',
  4149.             'name' => '',
  4150.             'labelType' => 0,
  4151.             'width' => 60,
  4152.             'pageWidth' => 6,
  4153.             'height' => 39,
  4154.             'pageHeight' => 2,
  4155.             'formatData' => '',
  4156.         );
  4157.         if ($request->isMethod('POST')) {
  4158.             $post $request->request;
  4159.             $exists_already 0;
  4160.             if ($request->request->get('formatId') != '') {
  4161.                 $query_here $this->getDoctrine()
  4162.                     ->getRepository('ApplicationBundle:LabelFormat')
  4163.                     ->findOneBy(
  4164.                         array(
  4165.                             'formatId' => $request->request->get('formatId')
  4166.                         )
  4167.                     );
  4168.                 if (!empty($query_here)) {
  4169.                     $exists_already 1;
  4170.                     $new $query_here;
  4171.                 } else
  4172.                     $new = new LabelFormat();
  4173.             } else
  4174.                 $new = new LabelFormat();
  4175.             $new->setName($request->request->get('name'));
  4176.             $new->setLabelType($request->request->get('labelType'));
  4177.             $new->setWidth($request->request->get('width'));
  4178.             $new->setHeight($request->request->get('height'));
  4179.             $new->setFormatCode($request->request->get('formatCode'));
  4180.             $new->setActive(GeneralConstant::ACTIVE);
  4181.             $new->setPageHeight($request->request->get('pageHeight'));
  4182.             $new->setPageWidth($request->request->get('pageWidth'));
  4183.             $new->setFormatData($request->request->get('formatData'));
  4184.             if ($exists_already == 0)
  4185.                 $new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4186.             $new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4187.             $new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
  4188.             $em $this->getDoctrine()->getManager();
  4189.             $em->persist($new);
  4190.             $em->flush();
  4191.         }
  4192.         if ($id != 0) {
  4193.             $query_here $this->getDoctrine()
  4194.                 ->getRepository('ApplicationBundle:LabelFormat')
  4195.                 ->findOneBy(
  4196.                     array(
  4197.                         'formatId' => $id
  4198.                     )
  4199.                 );
  4200.             if ($query_here)
  4201.                 $data $query_here;
  4202.         } else if ($request->query->has('formatId')) {
  4203.             $query_here $this->getDoctrine()
  4204.                 ->getRepository('ApplicationBundle:LabelFormat')
  4205.                 ->findOneBy(
  4206.                     array(
  4207.                         'formatId' => $request->query->get('formatId')
  4208.                     )
  4209.                 );
  4210.             if ($query_here)
  4211.                 $data $query_here;
  4212.         }
  4213.         return $this->render(
  4214.             'ApplicationBundle:pages/inventory/input_forms:label_format.html.twig',
  4215.             array(
  4216.                 'page_title' => 'Label Format',
  4217.                 'data' => $data,
  4218.                 'labelTypeList' => LabelConstant::$label_type_list,
  4219.                 'labelFieldsList' => LabelConstant::$label_fields_list,
  4220.                 'formatList' => $this->getDoctrine()
  4221.                     ->getRepository('ApplicationBundle:LabelFormat')
  4222.                     ->findBy(
  4223.                         array( //                            'formatId' => $request->query->get('formatId')
  4224.                         )
  4225.                     )
  4226.                 //                'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
  4227.             )
  4228.         );
  4229.     }
  4230.     public function GetServiceListForScAction(Request $request)
  4231.     {
  4232.         if ($request->isMethod('POST')) {
  4233.             $em $this->getDoctrine();
  4234.             $find_array = array(
  4235.                 'type' => 2//service
  4236.             );
  4237.             $Content = [];
  4238.             $Transport_data = [];
  4239.             $Lul_data = [];
  4240.             if ($request->request->get('soId') != '')
  4241.                 $find_array['salesOrderId'] = $request->request->get('soId');
  4242. //            if($request->request->get('warehouseId')!='')
  4243. //                $find_array['warehouseId']=$request->request->get('warehouseId');
  4244.             $QD $this->getDoctrine()
  4245.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  4246.                 ->findBy(
  4247.                     $find_array,
  4248.                     array()
  4249.                 );
  4250. //            if($request->request->get('wareHouseId')!='')
  4251.             $SO $this->getDoctrine()
  4252.                 ->getRepository('ApplicationBundle:SalesOrder')
  4253.                 ->findOneBy(
  4254.                     array(
  4255.                         'salesOrderId' => $request->request->get('soId')
  4256.                     ),
  4257.                     array()
  4258.                 );
  4259.             $sendData = array(
  4260. //                'salesType'=>$SO->getSalesType(),
  4261. //                'packageData'=>[],
  4262.                 'productList' => [],
  4263. //                'productListByPackage'=>[],
  4264.             );
  4265.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  4266.             $pckg_item_cross_match_data = [];
  4267.             foreach ($QD as $product) {
  4268.                 $p_data = array(
  4269.                     'details_id' => $product->getId(),
  4270.                     'service_id' => $product->getServiceId(),
  4271.                     'service_name' => $serviceList[$product->getServiceId()]['name'],
  4272.                     'available_inventory' => $product->getBalance(),
  4273. //                        'package_id'=>$product->getPackageId(),
  4274.                     'qty' => $product->getQty(),
  4275.                     'delivered' => $product->getDelivered(),
  4276. //                    'deliverable'=>$product->getDeliverable(),
  4277.                     'balance' => $product->getBalance(),
  4278. //                        'delivered'=>$product->getDelivered(),
  4279.                 );
  4280.                 $sendData['serviceList'][] = $p_data;
  4281.             }
  4282.             //now package data
  4283.             if ($sendData) {
  4284.                 return new JsonResponse(array("success" => true"content" => $sendData));
  4285.             }
  4286.             return new JsonResponse(array("success" => false));
  4287.         }
  4288.         return new JsonResponse(array("success" => false));
  4289.     }
  4290.     public function CreateReceivedNoteAction(Request $request)
  4291.     {
  4292.         if ($request->isMethod('POST')) {
  4293.             $em $this->getDoctrine()->getManager();
  4294.             $entity_id array_flip(GeneralConstant::$Entity_list)['Grn']; //change
  4295.             $dochash $request->request->get('docHash'); //change
  4296.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4297.             $approveRole 1;  //created
  4298.             $approveHash $request->request->get('approvalHash');
  4299.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4300.                 $loginId$approveRole$approveHash)
  4301.             ) {
  4302.                 $this->addFlash(
  4303.                     'error',
  4304.                     'Sorry Couldnot insert Data.'
  4305.                 );
  4306.             } else {
  4307.                 $data $request->request;
  4308.                 $grnId Inventory::CreateGrn($this->getDoctrine()->getManager(), $data$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4309.                 //now add Approval info
  4310.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4311.                 $approveRole 1;  //created
  4312.                 $options = array(
  4313.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4314.                     'notification_server' => $this->container->getParameter('notification_server'),
  4315.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4316.                     'url' => $this->generateUrl(
  4317.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['Grn']]
  4318.                         ['entity_view_route_path_name']
  4319.                     )
  4320.                 );
  4321.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  4322.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  4323.                     $grnId,
  4324.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  4325.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
  4326.                     $loginId,
  4327.                     $approveRole,
  4328.                     $request->request->get('approvalHash'));
  4329.                 $this->addFlash(
  4330.                     'success',
  4331.                     'New GRN Added.'
  4332.                 );
  4333.                 $url $this->generateUrl(
  4334.                     'view_grn'
  4335.                 );
  4336.                 System::AddNewNotification($this->container->getParameter('notification_enabled'), $this->container->getParameter('notification_server'), $request->getSession()->get(UserConstants::USER_APP_ID), $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  4337.                     "Good Received Note : " $dochash " Has Been Created And is Under Processing",
  4338.                     'pos',
  4339.                     System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENTGeneralConstant::PURCHASE_DEPARTMENTGeneralConstant::ACCOUNTS_DEPARTMENTGeneralConstant::INVENTORY_DEPARTMENT]),
  4340.                     'success',
  4341.                     $url "/" $grnId,
  4342.                     "GRN"
  4343.                 );
  4344.                 return $this->redirect($url "/" $grnId);
  4345.             }
  4346.         }
  4347.         return $this->render('ApplicationBundle:pages/inventory/input_forms:received_note.html.twig',
  4348.             array(
  4349.                 'page_title' => 'GRN',
  4350.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  4351.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  4352.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  4353.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  4354.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  4355.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  4356.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  4357.                 'material_inward' => $this->getDoctrine()
  4358.                     ->getRepository('ApplicationBundle:MaterialInward')
  4359.                     ->findBy(
  4360.                         array(
  4361.                             'stage' => GeneralConstant::STAGE_PENDING_TAG
  4362.                         )
  4363.                     )
  4364. //                'po'=>Inventory::getPurchaseOrderList
  4365.             )
  4366.         );
  4367.     }
  4368.     public function GetQcListForGrnAction(Request $request)
  4369.     {
  4370.         if ($request->isMethod('POST')) {
  4371.             $find_array = array(
  4372.                 'stage' => GeneralConstant::STAGE_PENDING_TAG
  4373.             );
  4374.             $Content = [];
  4375.             $ContentByProductId = [];
  4376.             $Transport_data = [];
  4377.             $Lul_data = [];
  4378.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4379.             if ($request->request->get('poId') != '')
  4380.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4381.             if ($request->request->get('warehouseId') != '')
  4382.                 $find_array['warehouseId'] = $request->request->get('warehouseId');
  4383.             $QD $this->getDoctrine()
  4384.                 ->getRepository('ApplicationBundle:MaterialInward')
  4385.                 ->findBy(
  4386.                     $find_array,
  4387.                     array(
  4388.                         'inwardDate' => 'ASC',
  4389.                         'qcDate' => 'ASC'
  4390.                     )
  4391.                 );
  4392.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4393.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4394.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4395.             $lotNumArray = [];
  4396.             foreach ($QD as $entry) {
  4397. //                $inwardDate=strtotime($entry->getInwardDate());
  4398. //                $qcDate=strtotime($entry->getQcDate());
  4399.                 $inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
  4400.                 $qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
  4401.                 if (!in_array($entry->getLotNumber(), $lotNumArray))
  4402.                     $lotNumArray[] = $entry->getLotNumber();
  4403.                 if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
  4404.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
  4405.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
  4406.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
  4407.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
  4408.                     $ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += ($entry->getApprovedQty());
  4409.                 } else {
  4410.                     $ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
  4411.                         'productName' => $productList[$entry->getProductId()]['name'],
  4412.                         'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
  4413.                         'qcHash' => $entry->getDocumentHash(),
  4414.                         'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
  4415.                         'inwardDate' => $inwardDate,
  4416.                         'inwardDateList' => [$inwardDate],
  4417.                         'qcDateList' => [$qcDate],
  4418.                         'qcIdList' => [$entry->getQcId()],
  4419.                         'qcDate' => $qcDate,
  4420.                         'poQty' => $entry->getPoQty(),
  4421.                         'poPrevbalance' => $entry->getPoBalance(),
  4422.                         'appQty' => $entry->getApprovedQty(),
  4423.                         'appQtyList' => [$entry->getApprovedQty()],
  4424.                         'totQty' => $entry->getApprovedQty(),
  4425.                         'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
  4426.                         'qcId' => $entry->getQcId(),
  4427.                         'productId' => $entry->getProductId()
  4428.                     );
  4429.                 }
  4430.                 $Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
  4431.                 $Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
  4432.             }
  4433.             foreach ($ContentByProductId as $c) {
  4434.                 $Content[] = $c;
  4435.             }
  4436.             if ($QD) {
  4437.                 return new JsonResponse(array("success" => true"content" => $Content"lotNumber" => implode(', '$lotNumArray), 'Expense_Cost' => $Expense_Cost'Expense_Id' => $Expense_Id));
  4438.             }
  4439.             return new JsonResponse(array("success" => false));
  4440.         }
  4441.         return new JsonResponse(array("success" => false));
  4442.     }
  4443.     public function GetSrListForIrAction(Request $request)
  4444.     {
  4445.         if ($request->isMethod('POST')) {
  4446.             $find_array = array();
  4447.             $Content = [];
  4448.             if ($request->request->get('srId') != '')
  4449.                 $find_array['stockRequisitionId'] = $request->request->get('srId');
  4450.             $find_array['forceSkipTag'] = [0null];
  4451.             $QD $this->getDoctrine()
  4452.                 ->getRepository('ApplicationBundle:StockRequisitionItem')
  4453.                 ->findBy(
  4454.                     $find_array
  4455.                 );
  4456.             $itemList Inventory::ItemGroupList($this->getDoctrine()->getManager());
  4457.             $catgoryList Inventory::ProductCategoryList($this->getDoctrine()->getManager());
  4458.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4459.             $unitList Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4460.             $fdmData = array();
  4461.             $em $this->getDoctrine()->getManager();
  4462.             $matchType 'MAXIMUM';
  4463.             if ($request->request->has('matchType') != '') {
  4464.                 $matchType $request->request->get('matchType');
  4465.             }
  4466.             if ($matchType == 'MINIMUM') {
  4467.                 foreach ($QD as $entry) {
  4468.                     if ($entry->getTagPendingAmount() <= 0)
  4469.                         continue;
  4470.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4471.                     $combined_id $entry->getProductFdm();
  4472.                     if (isset($fdmData[$combined_id])) {
  4473.                         $fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
  4474.                         $fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
  4475.                         $fdmData[$combined_id]['detailsIds'][] = $entry->getId();
  4476.                         $fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
  4477.                     } else {
  4478.                         $fdmData[$combined_id] = array(
  4479.                             'id' => 0,
  4480.                             'alias' => $entry->getNote(),
  4481.                             'unit' => $entry->getTagPendingAmount(),
  4482.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4483.                             'warranty' => 0,
  4484.                             'unitTypeId' => 0,
  4485.                             'unit_price' => 0,
  4486.                             'fdm' => $combined_id,
  4487.                             'extDetailsId' => 0,
  4488.                             'product_name' => $productData['productName'],
  4489.                             'total_price' => 0,
  4490.                             'detailsIds' => [$entry->getId()],
  4491.                             'docIds' => [$entry->getStockRequisitionId()],
  4492.                         );
  4493.                     }
  4494.                 }
  4495.             }
  4496.             if ($matchType == 'MAXIMUM') {
  4497.                 foreach ($QD as $entry) {
  4498.                     if ($entry->getTagPendingAmount() <= 0)
  4499.                         continue;
  4500.                     $productData Inventory::GetProductDataFromFdm($em$entry->getProductFdm());
  4501.                     $combined_id $entry->getProductFdm();
  4502.                     $assigned 0;
  4503.                     foreach ($fdmData as $key_ind => $rel_val) {
  4504.                         $matchFdm Inventory::MatchFdm($key_ind$combined_id);
  4505.                         if ($matchFdm['hasMatched'] == 1) {
  4506.                             if ($matchFdm['isIdentical'] == 1) {
  4507.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4508.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4509.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4510.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4511.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4512.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4513.                                 $assigned 1;
  4514.                             } elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
  4515.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4516.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4517.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4518.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4519.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4520.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4521.                                 $assigned 1;
  4522.                             } elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
  4523.                                 $fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
  4524.                                 $fdmData[$key_ind]['alias'] .= (', ' $entry->getNote());
  4525.                                 $fdmData[$key_ind]['detailsIds'][] = $entry->getId();
  4526.                                 $fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
  4527.                                 $fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
  4528.                                 $fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
  4529.                                 $fdmData[$combined_id] = $fdmData[$key_ind];
  4530.                                 unset($fdmData[$key_ind]);
  4531.                                 $assigned 1;
  4532.                             }
  4533.                         } else {
  4534.                         }
  4535.                         if ($assigned == 1)
  4536.                             break;
  4537.                     }
  4538.                     if ($assigned == 0) {
  4539.                         $fdmData[$combined_id] = array(
  4540.                             'id' => 0,
  4541.                             'alias' => $entry->getNote(),
  4542.                             'unit' => $entry->getTagPendingAmount(),
  4543.                             'specific_unit' => [$entry->getTagPendingAmount()],
  4544.                             'specific_unit_type_id' => [$entry->getUnitTypeId()],
  4545.                             'warranty' => 0,
  4546.                             'unitTypeId' => $productData['unitTypeId'],
  4547. //                            'unitTypeId' => $productData['unitTypeId'],
  4548.                             'unit_price' => 0,
  4549.                             'fdm' => $combined_id,
  4550.                             'extDetailsId' => 0,
  4551.                             'product_name' => htmlspecialchars($productData['productName']),
  4552.                             'total_price' => 0,
  4553.                             'detailsIds' => [$entry->getId()],
  4554.                             'docIds' => [$entry->getStockRequisitionId()],
  4555.                         );
  4556.                     }
  4557.                     if (isset($fdmData[$combined_id])) {
  4558.                     } else {
  4559.                     }
  4560.                 }
  4561.             }
  4562.             $QD $this->getDoctrine()
  4563.                 ->getRepository('ApplicationBundle:StockRequisition')
  4564.                 ->findBy(
  4565.                     array('stockRequisitionId' => $request->request->get('srId'))
  4566.                 );
  4567.             $contentNote "";
  4568.             foreach ($QD as $r) {
  4569.                 $contentNote .= $r->getNote();
  4570.                 $contentNote .= " , ";
  4571.             }
  4572.             foreach ($fdmData as $dt) {
  4573.                 $Content[] = $dt;
  4574.             }
  4575.             if ($Content) {
  4576.                 return new JsonResponse(array("success" => true"content" => $Content"contentNote" => $contentNote));
  4577.             }
  4578.             return new JsonResponse(array("success" => false));
  4579.         }
  4580.         return new JsonResponse(array("success" => false));
  4581.     }
  4582.     public function GetGrnListForEiAction(Request $request)
  4583.     {
  4584.         if ($request->isMethod('POST')) {
  4585.             $find_array = array(
  4586.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4587.                 'approved' => GeneralConstant::APPROVED,
  4588.                 'invoiceTagged' => 1
  4589.             );
  4590.             $Content = [];
  4591.             $Content_obj = [];
  4592.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4593.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4594.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4595.             if ($request->request->get('poId') != '')
  4596.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4597.             if ($request->request->get('grnId') != '')
  4598.                 $find_array['grnId'] = $request->request->get('grnId');
  4599.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4600.             $QD_GRN $this->getDoctrine()
  4601.                 ->getRepository('ApplicationBundle:Grn')
  4602.                 ->findBy(
  4603.                     $find_array,
  4604.                     array(
  4605.                         'grnDate' => 'ASC'
  4606.                     )
  4607.                 );
  4608.             $poId 0;
  4609. //
  4610. //            $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
  4611. //                $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
  4612. //                $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
  4613.             $partyId $request->request->get('partyId');
  4614.             $bill_details = [];
  4615.             $bill_details_data = [];
  4616.             $bill_details_for_grn = [];
  4617.             $exp_list InventoryConstant::$Expense_list_details;
  4618.             $supp_list Inventory::ProductSupplierList($this->getDoctrine()->getManager());
  4619.             $head_qry $this->getDoctrine()
  4620.                 ->getRepository('ApplicationBundle:AccAccountsHead')
  4621.                 ->findAll();
  4622.             $head_list = [];
  4623.             $head_list_by_advance = [];
  4624.             foreach ($head_qry as $data) {
  4625.                 $head_list[$data->getAccountsHeadId()] = array(
  4626.                     'id' => $data->getAccountsHeadId(),
  4627.                     'name' => $data->getName(),
  4628.                     'advanceTagged' => $data->getAdvanceTagged(),
  4629.                     'advanceOf' => $data->getAdvanceOf(),
  4630.                     'balance' => $data->getCurrentBalance()
  4631.                 );
  4632.                 if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != && $data->getAdvanceOf() != '')
  4633.                     $head_list_by_advance[$data->getAdvanceOf()] = array(
  4634.                         'id' => $data->getAccountsHeadId(),
  4635.                         'name' => $data->getName(),
  4636.                         'advanceTagged' => $data->getAdvanceTagged(),
  4637.                         'advanceOf' => $data->getAdvanceOf(),
  4638.                         'balance' => $data->getCurrentBalance()
  4639.                     );
  4640.             }
  4641.             $exp_def_head = [];
  4642.             foreach ($exp_list as $key => $item) {
  4643.                 $def_settings $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  4644.                     'name' => $item['name'] . '_onsite_head'
  4645.                 ));
  4646.                 if ($def_settings)
  4647.                     $exp_def_head[$item['id']] = $def_settings->getData();
  4648.                 else
  4649.                     $exp_def_head[$item['id']] = '';
  4650.             }
  4651.             $bill_details_by_party = [];
  4652. //            System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
  4653. //            System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
  4654. //            System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
  4655. //
  4656.             foreach ($QD_GRN as $key => $value) {
  4657.                 $expense_id $value->getExpenseId() != '' json_decode($value->getExpenseId(), true) : [];
  4658.                 $expense_list $value->getExpenseCost() != '' json_decode($value->getExpenseCost(), true) : [];
  4659.                 $expense_tagged $value->getExpenseTagged() != '' json_decode($value->getExpenseTagged(), true) : [];
  4660. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
  4661. //                System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
  4662.                 foreach ($exp_list as $chabi => $entry) {
  4663. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
  4664. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
  4665.                     if (array_key_exists($chabi$expense_id)) {
  4666. //                    System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
  4667.                         if ($partyId == ''//all
  4668.                         {
  4669.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4670.                                 $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4671.                                 $advance_balance 0;
  4672.                                 if ($partyHeadId != 0) {
  4673.                                     $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4674.                                     $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4675.                                     $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4676.                                 }
  4677.                                 $bill_details_by_party[$my_val][] = array(
  4678.                                     'partyId' => $my_val,
  4679.                                     'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4680.                                     'partyHeadId' => $partyHeadId,
  4681.                                     'expTypeId' => $chabi,
  4682.                                     'expTypeName' => $exp_list[$chabi]['name'],
  4683.                                     'expTypeAlias' => $exp_list[$chabi]['alias'],
  4684.                                     'expAmount' => $expense_list[$chabi][$index],
  4685.                                     'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4686.                                     'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4687.                                     'AdvanceBalance' => $advance_balance,
  4688.                                     'grnId' => $value->getGrnId(),
  4689.                                     'grnName' => $value->getDocumentHash(),
  4690.                                 );
  4691.                             }
  4692.                         } else {
  4693.                             foreach ($expense_id[$chabi] as $index => $my_val) {
  4694.                                 if (in_array($my_val$partyId)) {
  4695.                                     $partyHeadId $my_val != $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
  4696.                                     $advance_balance 0;
  4697.                                     if ($partyHeadId != 0) {
  4698.                                         $curr $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
  4699.                                         $advance_balance = ($curr $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
  4700.                                         $head_list[$partyHeadId]['advanceTagged'] == ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
  4701.                                     }
  4702.                                     $bill_details_by_party[$my_val][] = array(
  4703.                                         'partyId' => $my_val,
  4704.                                         'partyName' => $my_val != $head_list[$my_val]['name'] : 'On site Payment',
  4705.                                         'partyHeadId' => $partyHeadId,
  4706.                                         'expTypeId' => $chabi,
  4707.                                         'expTypeName' => $exp_list[$chabi]['name'],
  4708.                                         'expTypeAlias' => $exp_list[$chabi]['alias'],
  4709.                                         'expAmount' => $expense_list[$chabi][$index],
  4710.                                         'hasAdvance' => $partyHeadId != $head_list[$partyHeadId]['advanceTagged'] : 0,
  4711.                                         'AdvanceHeadId' => $partyHeadId != ? ($head_list[$partyHeadId]['advanceTagged'] == $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
  4712.                                         'AdvanceBalance' => $advance_balance,
  4713.                                         'grnId' => $value->getGrnId(),
  4714.                                         'grnName' => $value->getDocumentHash(),
  4715.                                     );
  4716.                                 }
  4717.                             }
  4718.                         }
  4719.                     }
  4720.                 }
  4721.             }
  4722. //            $Content_obj=
  4723. //
  4724. //            foreach($Content_obj as $item)
  4725. //            {
  4726. //                $Content[]=$item;
  4727. //
  4728. //            }
  4729.             $list_of_keys array_keys($bill_details_by_party);
  4730.             if ($bill_details_by_party) {
  4731.                 return new JsonResponse(array("success" => true"content" => $bill_details_by_party'index' => $list_of_keys'h_l_b_a' => $head_list_by_advance));
  4732.             }
  4733.             return new JsonResponse(array("success" => false));
  4734.         }
  4735.         return new JsonResponse(array("success" => false));
  4736.     }
  4737.     public function GetServiceListForPiAction(Request $request)
  4738.     {
  4739.         if ($request->isMethod('POST')) {
  4740. //            $find_array=array(
  4741. //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG,
  4742. //                'approved'=>GeneralConstant::APPROVED
  4743. //            );
  4744.             $Content = [];
  4745.             $Content_obj = [];
  4746.             $ContentService = [];
  4747.             $Content_service_obj = [];
  4748. //            $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
  4749. //            $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4750. //            $productList=Inventory::ProductList($this->getDoctrine()->getManager());
  4751.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4752.             if ($request->request->get('poId') != '')
  4753.                 $poId $request->request->get('poId');
  4754.             if ($request->request->get('grnId') != '')
  4755.                 $find_array['grnId'] = $request->request->get('grnId');
  4756.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4757.             //adding service data temporarily
  4758.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4759.                 array('purchaseOrderId' => $poId));
  4760.             $multiply_type $po->getCurrencyMultiply();
  4761.             $multiply_rate $po->getCurrencyMultiplyRate();
  4762.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4763.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4764.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4765.                 array('purchaseOrderId' => $poId));
  4766.             foreach ($po_items as $item) {
  4767. //                $po_item_list[$item->getProductId()]=$item;
  4768.                 //temporary service add
  4769.                 if ($item->getType() == 2)
  4770.                     $Content_service_obj[$item->getId()] = array(
  4771.                         'serviceId' => $item->getServiceId(),
  4772.                         'poItemId' => $item->getId(),
  4773.                         'colorId' => 0,
  4774.                         'sizeId' => 0,
  4775.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4776.                         'qty' => $item->getQty(),
  4777.                         'balance' => $item->getBalance(),
  4778.                         'unit_name' => '',
  4779.                         'unit_price' => $item->getPrice() * $multiplier,
  4780.                         'grn_id' => 0,
  4781.                     );
  4782.                 //temprary service add end
  4783.             }
  4784.             //temporary service data adding done
  4785.             $po_data = [];
  4786.             $po_data = array(
  4787.                 'docHash' => $po->getDocumentHash(),
  4788.                 'docDate' => $po->getPurchaseOrderDate(),
  4789.                 'supplierId' => $po->getSupplierId(),
  4790.                 'supplierName' => $po->getSupplierId(),
  4791.                 'vatRate' => $po->getVatRate(),
  4792.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4793.                 'aitRate' => $po->getAitRate(),
  4794.                 'aitAmount' => $po->getAitAmount(),
  4795.                 'tdsRate' => $po->getTdsRate(),
  4796.                 'tdsAmount' => $po->getTdsAmount(),
  4797.                 'vdsRate' => $po->getVdsRate(),
  4798.                 'vdsAmount' => $po->getVdsAmount(),
  4799.                 'discountRate' => $po->getDiscountRate(),
  4800.                 'discountAmount' => $po->getVatAmount(),
  4801.             );
  4802.             foreach ($Content_obj as $item) {
  4803.                 $Content[] = $item;
  4804.             }
  4805.             foreach ($Content_service_obj as $item) {
  4806.                 $ContentService[] = $item;
  4807.             }
  4808.             if ($Content || $ContentService) {
  4809.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4810.             }
  4811.             return new JsonResponse(array("success" => false));
  4812.         }
  4813.         return new JsonResponse(array("success" => false));
  4814.     }
  4815.     public function GetGrnListForPiAction(Request $request)
  4816.     {
  4817.         if ($request->isMethod('POST')) {
  4818.             $find_array = array(
  4819.                 'stage' => GeneralConstant::STAGE_PENDING_TAG,
  4820.                 'approved' => GeneralConstant::APPROVED
  4821.             );
  4822.             $Content = [];
  4823.             $Content_obj = [];
  4824.             $ContentService = [];
  4825.             $Content_service_obj = [];
  4826.             $warehouse Inventory::WarehouseList($this->getDoctrine()->getManager());
  4827.             $poList Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
  4828.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4829.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager());
  4830.             if ($request->request->get('poId') != '')
  4831.                 $find_array['purchaseOrderId'] = $request->request->get('poId');
  4832.             if ($request->request->get('grnId') != '')
  4833.                 $find_array['grnId'] = $request->request->get('grnId');
  4834.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4835.             $QD_GRN $this->getDoctrine()
  4836.                 ->getRepository('ApplicationBundle:Grn')
  4837.                 ->findBy(
  4838.                     $find_array,
  4839.                     array(
  4840.                         'grnDate' => 'ASC'
  4841.                     )
  4842.                 );
  4843.             $poId 0;
  4844.             foreach ($QD_GRN as $value) {
  4845.                 $grn_items $this->getDoctrine()->getRepository('ApplicationBundle:GrnItem')->findBy(
  4846.                     array('grnId' => $value->getGrnId()));
  4847.                 $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4848.                     array('purchaseOrderId' => $value->getPurchaseOrderId()));
  4849.                 $poId $value->getPurchaseOrderId();
  4850.                 $po_item_list = [];
  4851.                 foreach ($po_items as $item) {
  4852.                     $po_item_list[$item->getProductId()] = $item;
  4853.                 }
  4854.                 foreach ($grn_items as $entry) {
  4855.                     //adding transaction
  4856. //                    System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
  4857.                     $Content_obj[$entry->getId()] = array(
  4858.                         'productId' => $entry->getProductId(),
  4859.                         'poItemId' => $entry->getId(),
  4860.                         'productName' => $productList[$entry->getProductId()]['name'],
  4861.                         'colorId' => $entry->getColorId(),
  4862.                         'sizeId' => $entry->getSizeId(),
  4863.                         'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
  4864.                         'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4865. //                            'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
  4866.                         'unit_price' => $entry->getPrice(),
  4867.                         'grn_id' => $entry->getId(),
  4868.                     );
  4869.                 }
  4870. //            for
  4871.             }
  4872.             //adding service data temporarily
  4873.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
  4874.                 array('purchaseOrderId' => $poId));
  4875.             $multiply_type $po->getCurrencyMultiply();
  4876.             $multiply_rate $po->getCurrencyMultiplyRate();
  4877.             $multiplier = ($multiply_type 1) == ? ($multiply_rate) :
  4878.                 (($multiply_rate 1) != ? ($multiply_rate) : 1);
  4879.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4880.                 array('purchaseOrderId' => $poId));
  4881.             foreach ($po_items as $item) {
  4882. //                $po_item_list[$item->getProductId()]=$item;
  4883.                 //temporary service add
  4884.                 if ($item->getType() == 2)
  4885.                     $Content_service_obj[$item->getId()] = array(
  4886.                         'serviceId' => $item->getServiceId(),
  4887.                         'poItemId' => $item->getId(),
  4888.                         'colorId' => 0,
  4889.                         'sizeId' => 0,
  4890.                         'serviceName' => $serviceList[$item->getServiceId()]['name'],
  4891.                         'qty' => $item->getQty(),
  4892.                         'balance' => $item->getBalance(),
  4893.                         'unit_name' => '',
  4894.                         'unit_price' => $item->getPrice() * $multiplier,
  4895.                         'grn_id' => 0,
  4896.                     );
  4897.                 //temprary service add end
  4898.             }
  4899.             //temporary service data adding done
  4900.             $po_data = [];
  4901.             $po_data = array(
  4902.                 'docHash' => $po->getDocumentHash(),
  4903.                 'docDate' => $po->getPurchaseOrderDate(),
  4904.                 'supplierId' => $po->getSupplierId(),
  4905.                 'supplierName' => $po->getSupplierId(),
  4906.                 'vatRate' => $po->getVatRate(),
  4907.                 'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
  4908.                 'aitRate' => $po->getAitRate(),
  4909.                 'aitAmount' => $po->getAitAmount(),
  4910.                 'tdsRate' => $po->getTdsRate(),
  4911.                 'tdsAmount' => $po->getTdsAmount(),
  4912.                 'vdsRate' => $po->getVdsRate(),
  4913.                 'vdsAmount' => $po->getVdsAmount(),
  4914.                 'discountRate' => $po->getDiscountRate(),
  4915.                 'discountAmount' => $po->getVatAmount(),
  4916.             );
  4917.             foreach ($Content_obj as $item) {
  4918.                 $Content[] = $item;
  4919.             }
  4920.             foreach ($Content_service_obj as $item) {
  4921.                 $ContentService[] = $item;
  4922.             }
  4923.             if ($Content) {
  4924.                 return new JsonResponse(array("success" => true"content" => $Content"contentService" => $ContentService"po_data" => $po_data));
  4925.             }
  4926.             return new JsonResponse(array("success" => false));
  4927.         }
  4928.         return new JsonResponse(array("success" => false));
  4929.     }
  4930.     public function GetPoDetailsForPiAction(Request $request$poId)
  4931.     {
  4932.     }
  4933.     public function GetPoDetailsAction(Request $request$poId)
  4934.     {
  4935.         if ($request->isMethod('POST')) {
  4936.             $po $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findBy(
  4937.                 array('purchaseOrderId' => $poId));
  4938.             $po_items $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
  4939.                 array('purchaseOrderId' => $poId));
  4940.             $productList Inventory::ProductList($this->getDoctrine()->getManager());
  4941.             $unit_type Inventory::UnitTypeList($this->getDoctrine()->getManager());
  4942.             $Content = [];
  4943.             $po_items_list = [];
  4944.             foreach ($po_items as $entry) {
  4945.                 $po_items_list[] = array(
  4946.                     'productId' => $entry->getProductId(),
  4947.                     'productName' => $productList[$entry->getProductId()]['name'],
  4948.                     'price' => $entry->getPrice(),
  4949.                     'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
  4950.                     'received' => $entry->getReceived(),
  4951.                     'qty' => $entry->getQty(),
  4952.                     'balance' => $entry->getBalance()
  4953.                 );
  4954.             }
  4955.             $po_data = [];
  4956.             $po_data = array(
  4957.                 'docHash' => $po->getDocumentHash(),
  4958.                 'docDate' => $po->getPurchaseOrderDate(),
  4959.                 'supplierId' => $po->getSupplierId(),
  4960.                 'supplierName' => $po->getSupplierId(),
  4961.             );
  4962.             if ($po_data) {
  4963.                 return new JsonResponse(array("success" => true"content" => $po_data));
  4964.             }
  4965.             return new JsonResponse(array("success" => false));
  4966.         }
  4967.         return new JsonResponse(array("success" => false));
  4968.     }
  4969.     public function CreateSalesReplacementAction(Request $request)
  4970.     {
  4971.         $em $this->getDoctrine()->getManager();
  4972.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4973.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4974.         if ($request->isMethod('POST')) {
  4975.             $em $this->getDoctrine()->getManager();
  4976.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReplacement']; //change
  4977.             $dochash $request->request->get('voucherNumber'); //change
  4978.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4979.             $approveRole $request->request->get('approvalRole');
  4980.             $approveHash $request->request->get('approvalHash');
  4981.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  4982.                 $loginId$approveRole$approveHash)
  4983.             ) {
  4984.                 $this->addFlash(
  4985.                     'error',
  4986.                     'Sorry Couldnot insert Data.'
  4987.                 );
  4988.             } else {
  4989.                 if ($request->request->has('check_allowed'))
  4990.                     $check_allowed 1;
  4991.                 $StID Inventory::CreateNewSalesReplacement(
  4992.                     $this->getDoctrine()->getManager(),
  4993.                     $request->request,
  4994.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4995.                     $this->getLoggedUserCompanyId($request)
  4996.                 );
  4997.                 //now add Approval info
  4998.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4999.                 $approveRole 1;  //created
  5000.                 $options = array(
  5001.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5002.                     'notification_server' => $this->container->getParameter('notification_server'),
  5003.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5004.                     'url' => $this->generateUrl(
  5005.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReplacement']]
  5006.                         ['entity_view_route_path_name']
  5007.                     )
  5008.                 );
  5009.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5010.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5011.                     $StID,
  5012.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5013.                 );
  5014.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
  5015.                     $loginId,
  5016.                     $approveRole,
  5017.                     $request->request->get('approvalHash'));
  5018.                 $this->addFlash(
  5019.                     'success',
  5020.                     'Stock Transfer Added.'
  5021.                 );
  5022.                 $url $this->generateUrl(
  5023.                     'view_st'
  5024.                 );
  5025.                 return $this->redirect($url "/" $StID);
  5026.             }
  5027.         }
  5028.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5029.             array(
  5030.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5031.             )
  5032.         );
  5033.         $INVLIST = [];
  5034.         foreach ($slotList as $slot) {
  5035.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5036.         }
  5037.         return $this->render('ApplicationBundle:pages/inventory/input_forms:sales_replacement.html.twig',
  5038.             array(
  5039.                 'page_title' => 'Sales Replacement Note',
  5040.                 'warehouseList' => Inventory::WarehouseList($em),
  5041.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5042.                 'warehouseActionList' => $warehouse_action_list,
  5043.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5044.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5045.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5046.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5047.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5048.                 'prefix_list' => array(
  5049.                     [
  5050.                         'id' => 1,
  5051.                         'value' => 'GN',
  5052.                         'text' => 'GN'
  5053.                     ]
  5054.                 ),
  5055.                 'assoc_list' => array(
  5056.                     [
  5057.                         'id' => 1,
  5058.                         'value' => 1,
  5059.                         'text' => 'GN'
  5060.                     ]
  5061.                 ),
  5062.                 'INVLIST' => $INVLIST
  5063.             )
  5064.         );
  5065.     }
  5066.     public function SalesReplacementListAction(Request $request)
  5067.     {
  5068.         $q $this->getDoctrine()
  5069.             ->getRepository('ApplicationBundle:SalesReplacement')
  5070.             ->findBy(
  5071.                 array(
  5072.                     'status' => GeneralConstant::ACTIVE,
  5073.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5074. //                    'approved' =>  GeneralConstant::APPROVED,
  5075.                 )
  5076.             );
  5077.         $stage_list = array(
  5078.             => 'Pending',
  5079.             => 'Pending',
  5080.             => 'Complete',
  5081.             => 'Partial',
  5082.         );
  5083.         $data = [];
  5084.         foreach ($q as $entry) {
  5085.             $data[] = array(
  5086.                 'doc_date' => $entry->getSalesReplacementDate(),
  5087.                 'id' => $entry->getSalesReplacementId(),
  5088.                 'doc_hash' => $entry->getDocumentHash(),
  5089.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5090.                 'stage' => $stage_list[$entry->getStage()]
  5091.             );
  5092.         }
  5093.         return $this->render('ApplicationBundle:pages/inventory/view:stock_transfer_list.html.twig',
  5094.             array(
  5095.                 'page_title' => 'Stock Transfer List',
  5096.                 'data' => $data
  5097.             )
  5098.         );
  5099.     }
  5100.     public function ViewSalesReplacementAction(Request $request$id)
  5101.     {
  5102.         $em $this->getDoctrine()->getManager();
  5103.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5104.         return $this->render('ApplicationBundle:pages/inventory/view:view_stock_transfer.html.twig',
  5105.             array(
  5106.                 'page_title' => 'Stock Transfer',
  5107.                 'data' => $dt,
  5108.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5109.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5110.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5111.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5112.                     $id,
  5113.                     $dt['created_by'],
  5114.                     $dt['edited_by'])
  5115.             )
  5116.         );
  5117.     }
  5118.     public function PrintSalesReplacementAction(Request $request$id)
  5119.     {
  5120.         $em $this->getDoctrine()->getManager();
  5121.         $dt Inventory::GetSalesReplacementDetails($em$id);
  5122.         $company_data Company::getCompanyData($em1);
  5123.         $document_mark = array(
  5124.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5125.             'copy' => ''
  5126.         );
  5127.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5128.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
  5129.                 array(
  5130.                     //full array here
  5131.                     'pdf' => true,
  5132.                     'page_title' => 'Stock Transfer',
  5133.                     'export' => 'pdf,print',
  5134.                     'data' => $dt,
  5135.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5136.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5137.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5138.                         array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5139.                         $id,
  5140.                         $dt['created_by'],
  5141.                         $dt['edited_by']),
  5142.                     'document_mark_image' => $document_mark['original'],
  5143.                     'company_name' => $company_data->getName(),
  5144.                     'company_data' => $company_data,
  5145.                     'company_address' => $company_data->getAddress(),
  5146.                     'company_image' => $company_data->getImage(),
  5147.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5148.                     'red' => 0
  5149.                 )
  5150.             );
  5151.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5152. //                'orientation' => 'landscape',
  5153. //                'enable-javascript' => true,
  5154. //                'javascript-delay' => 1000,
  5155.                 'no-stop-slow-scripts' => false,
  5156.                 'no-background' => false,
  5157.                 'lowquality' => false,
  5158.                 'encoding' => 'utf-8',
  5159. //            'images' => true,
  5160. //            'cookie' => array(),
  5161.                 'dpi' => 300,
  5162.                 'image-dpi' => 300,
  5163. //                'enable-external-links' => true,
  5164. //                'enable-internal-links' => true
  5165.             ));
  5166.             return new Response(
  5167.                 $pdf_response,
  5168.                 200,
  5169.                 array(
  5170.                     'Content-Type' => 'application/pdf',
  5171.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5172.                 )
  5173.             );
  5174.         }
  5175.         return $this->render('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
  5176.             array(
  5177.                 'page_title' => 'Stock Transfer',
  5178.                 'export' => 'pdf,print',
  5179.                 'data' => $dt,
  5180.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5181.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5182.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5183.                     array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
  5184.                     $id,
  5185.                     $dt['created_by'],
  5186.                     $dt['edited_by']),
  5187.                 'document_mark_image' => $document_mark['original'],
  5188.                 'company_name' => $company_data->getName(),
  5189.                 'company_data' => $company_data,
  5190.                 'company_address' => $company_data->getAddress(),
  5191.                 'company_image' => $company_data->getImage(),
  5192.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5193.                 'red' => 0
  5194.             )
  5195.         );
  5196.     }
  5197.     public function CreateStockTransferAction(Request $request)
  5198.     {
  5199.         $em $this->getDoctrine()->getManager();
  5200.         $companyId $this->getLoggedUserCompanyId($request);
  5201.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5202.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5203.         if ($request->isMethod('POST')) {
  5204.             $em $this->getDoctrine()->getManager();
  5205.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockTransfer']; //change
  5206.             $dochash $request->request->get('docHash'); //change
  5207.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5208.             $approveRole $request->request->get('approvalRole');
  5209.             $approveHash $request->request->get('approvalHash');
  5210.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5211.                 $loginId$approveRole$approveHash)
  5212.             ) {
  5213.                 $this->addFlash(
  5214.                     'error',
  5215.                     'Sorry Couldnot insert Data.'
  5216.                 );
  5217.             } else {
  5218.                 if ($request->request->has('check_allowed'))
  5219.                     $check_allowed 1;
  5220.                 $StID Inventory::CreateNewStockTransfer(
  5221.                     $this->getDoctrine()->getManager(),
  5222.                     $request->request,
  5223.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5224.                     $this->getLoggedUserCompanyId($request)
  5225.                 );
  5226.                 //now add Approval info
  5227.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5228.                 $approveRole 1;  //created
  5229.                 $options = array(
  5230.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5231.                     'notification_server' => $this->container->getParameter('notification_server'),
  5232.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5233.                     'url' => $this->generateUrl(
  5234.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockTransfer']]
  5235.                         ['entity_view_route_path_name']
  5236.                     )
  5237.                 );
  5238.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5239.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5240.                     $StID,
  5241.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
  5242.                 );
  5243.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
  5244.                     $loginId,
  5245.                     $approveRole,
  5246.                     $request->request->get('approvalHash'));
  5247.                 $this->addFlash(
  5248.                     'success',
  5249.                     'Stock Transfer Added.'
  5250.                 );
  5251.                 $url $this->generateUrl(
  5252.                     'view_st'
  5253.                 );
  5254.                 return $this->redirect($url "/" $StID);
  5255.             }
  5256.         }
  5257. //        $slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5258. //            array(
  5259. //                'CompanyId' => $this->getLoggedUserCompanyId($request),
  5260. //
  5261. //            )
  5262. //        );
  5263.         $INVLIST = [];
  5264. //        foreach ($slotList as $slot) {
  5265. //            $INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
  5266. //        }
  5267.         return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_transfer_note.html.twig',
  5268.             array(
  5269.                 'page_title' => 'Stock Transfer Note',
  5270.                 'warehouseList' => Inventory::WarehouseList($em),
  5271.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5272.                 'colorList' => Inventory::GetColorList($em),
  5273.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  5274.                 'srList' => [],
  5275.                 'warehouseActionList' => $warehouse_action_list,
  5276.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5277.                 'item_list' => Inventory::ItemGroupList($em),
  5278.                 'item_list_array' => Inventory::ItemGroupListArray($em),
  5279.                 'category_list_array' => Inventory::ProductCategoryListArray($em),
  5280.                 'product_list_array' => Inventory::ProductListDetailedArray($em),
  5281. //                'product_list_array' => [],
  5282.                 'product_list' => Inventory::ProductList($em$companyId),
  5283. //                'product_list' => [],
  5284.                 'prefix_list' => array(
  5285.                     [
  5286.                         'id' => 1,
  5287.                         'value' => 'GN',
  5288.                         'text' => 'GN'
  5289.                     ]
  5290.                 ),
  5291.                 'assoc_list' => array(
  5292.                     [
  5293.                         'id' => 1,
  5294.                         'value' => 1,
  5295.                         'text' => 'GN'
  5296.                     ]
  5297.                 ),
  5298.                 'INVLIST' => $INVLIST
  5299.             )
  5300.         );
  5301.     }
  5302.     public function GetSrItemForTransferAction(Request $request)
  5303.     {
  5304.         $em $this->getDoctrine()->getManager();
  5305.         $search_query = [];
  5306.         $res_data_by_so_item_id = [];
  5307.         $Content = [];
  5308.         $productionProcessSettings = array(
  5309.             'id' => 0
  5310.         );
  5311.         if ($request->query->has('srId'))
  5312.             $search_query['stockRequisitionId'] = $request->query->get('srId');
  5313.         $DT $this->getDoctrine()
  5314.             ->getRepository('ApplicationBundle:StockRequisitionItem')
  5315.             ->findBy(
  5316.                 $search_query
  5317.             );
  5318.         $Content = array(
  5319.             'requisitioned_product_item_id' => [],
  5320.             'requisitioned_products' => [],
  5321.             'requisitioned_product_fdm' => [],
  5322.             'requisitioned_product_name' => [],
  5323.             'requisitioned_product_units' => [],
  5324.             'requisitioned_product_unit_type' => [],
  5325.             'requisitioned_product_balance' => [],
  5326.         );
  5327.         foreach ($DT as $dt) {
  5328. //            $data=json_decode($DT->getData(),true);
  5329.             $Content['requisitioned_products'][] = $dt->getProductId();
  5330.             $Content['requisitioned_product_item_id'][] = $dt->getId();
  5331.             $Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
  5332.             $Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
  5333.             $Content['requisitioned_product_units'][] = $dt->getQty();
  5334.             $Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
  5335.         }
  5336.         $INVLIST = [];
  5337.         if (!empty($Content)) {
  5338.             return new JsonResponse(array("success" => true"content" => $Content"INVLIST" => $INVLIST));
  5339.         } else {
  5340.             return new JsonResponse(array("success" => false"content" => $Content"INVLIST" => $INVLIST));
  5341.         }
  5342.     }
  5343.     public function StockTransferListAction(Request $request)
  5344.     {
  5345.         $q $this->getDoctrine()
  5346.             ->getRepository('ApplicationBundle:StockTransfer')
  5347.             ->findBy(
  5348.                 array(
  5349.                     'status' => GeneralConstant::ACTIVE,
  5350.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5351. //                    'approved' =>  GeneralConstant::APPROVED,
  5352.                 )
  5353.             );
  5354.         $stage_list = array(
  5355.             => 'Pending',
  5356.             => 'Pending',
  5357.             => 'Complete',
  5358.             => 'Partial',
  5359.         );
  5360.         $data = [];
  5361.         foreach ($q as $entry) {
  5362.             $data[] = array(
  5363.                 'doc_date' => $entry->getStockTransferDate(),
  5364.                 'id' => $entry->getStockTransferId(),
  5365.                 'doc_hash' => $entry->getDocumentHash(),
  5366.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5367.                 'stage' => $stage_list[$entry->getStage()]
  5368.             );
  5369.         }
  5370.         return $this->render('ApplicationBundle:pages/inventory/view:stock_transfer_list.html.twig',
  5371.             array(
  5372.                 'page_title' => 'Stock Transfer List',
  5373.                 'data' => $data
  5374.             )
  5375.         );
  5376.     }
  5377.     public function ViewStockTransferAction(Request $request$id)
  5378.     {
  5379.         $em $this->getDoctrine()->getManager();
  5380.         $dt Inventory::GetStockTransferDetails($em$id);
  5381.         return $this->render('ApplicationBundle:pages/inventory/view:view_stock_transfer.html.twig',
  5382.             array(
  5383.                 'page_title' => 'Stock Transfer',
  5384.                 'data' => $dt,
  5385.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5386.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5387.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5388.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5389.                     $id,
  5390.                     $dt['created_by'],
  5391.                     $dt['edited_by'])
  5392.             )
  5393.         );
  5394.     }
  5395.     public function PrintStockTransferAction(Request $request$id)
  5396.     {
  5397.         $em $this->getDoctrine()->getManager();
  5398.         $dt Inventory::GetStockTransferDetails($em$id);
  5399.         $company_data Company::getCompanyData($em1);
  5400.         $document_mark = array(
  5401.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5402.             'copy' => ''
  5403.         );
  5404.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5405.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
  5406.                 array(
  5407.                     //full array here
  5408.                     'pdf' => true,
  5409.                     'page_title' => 'Stock Transfer',
  5410.                     'export' => 'pdf,print',
  5411.                     'data' => $dt,
  5412.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5413.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5414.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5415.                         array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5416.                         $id,
  5417.                         $dt['created_by'],
  5418.                         $dt['edited_by']),
  5419.                     'document_mark_image' => $document_mark['original'],
  5420.                     'company_name' => $company_data->getName(),
  5421.                     'company_data' => $company_data,
  5422.                     'company_address' => $company_data->getAddress(),
  5423.                     'company_image' => $company_data->getImage(),
  5424.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5425.                     'red' => 0
  5426.                 )
  5427.             );
  5428.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5429. //                'orientation' => 'landscape',
  5430. //                'enable-javascript' => true,
  5431. //                'javascript-delay' => 1000,
  5432.                 'no-stop-slow-scripts' => false,
  5433.                 'no-background' => false,
  5434.                 'lowquality' => false,
  5435.                 'encoding' => 'utf-8',
  5436. //            'images' => true,
  5437. //            'cookie' => array(),
  5438.                 'dpi' => 300,
  5439.                 'image-dpi' => 300,
  5440. //                'enable-external-links' => true,
  5441. //                'enable-internal-links' => true
  5442.             ));
  5443.             return new Response(
  5444.                 $pdf_response,
  5445.                 200,
  5446.                 array(
  5447.                     'Content-Type' => 'application/pdf',
  5448.                     'Content-Disposition' => 'attachment; filename="stock_transfer_' $id '.pdf"'
  5449.                 )
  5450.             );
  5451.         }
  5452.         return $this->render('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
  5453.             array(
  5454.                 'page_title' => 'Stock Transfer',
  5455.                 'export' => 'pdf,print',
  5456.                 'data' => $dt,
  5457.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5458.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5459.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5460.                     array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
  5461.                     $id,
  5462.                     $dt['created_by'],
  5463.                     $dt['edited_by']),
  5464.                 'document_mark_image' => $document_mark['original'],
  5465.                 'company_name' => $company_data->getName(),
  5466.                 'company_data' => $company_data,
  5467.                 'company_address' => $company_data->getAddress(),
  5468.                 'company_image' => $company_data->getImage(),
  5469.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5470.                 'red' => 0
  5471.             )
  5472.         );
  5473.     }
  5474.     public function CreateStockConsumptionNoteAction(Request $request)
  5475.     {
  5476.         $em $this->getDoctrine()->getManager();
  5477.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  5478.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  5479.         if ($request->isMethod('POST')) {
  5480.             $em $this->getDoctrine()->getManager();
  5481.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']; //change
  5482.             $dochash $request->request->get('voucherNumber'); //change
  5483.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5484.             $approveRole $request->request->get('approvalRole');
  5485.             $approveHash $request->request->get('approvalHash');
  5486.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5487.                 $loginId$approveRole$approveHash)
  5488.             ) {
  5489.                 $this->addFlash(
  5490.                     'error',
  5491.                     'Sorry Could not insert Data.'
  5492.                 );
  5493.             } else {
  5494.                 if ($request->request->has('check_allowed'))
  5495.                     $check_allowed 1;
  5496.                 $StID Inventory::CreateNewStockConsumptionNote(
  5497.                     $this->getDoctrine()->getManager(),
  5498.                     $request->request,
  5499.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5500.                     $this->getLoggedUserCompanyId($request)
  5501.                 );
  5502.                 //now add Approval info
  5503.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5504.                 $approveRole 1;  //created
  5505.                 $options = array(
  5506.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5507.                     'notification_server' => $this->container->getParameter('notification_server'),
  5508.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5509.                     'url' => $this->generateUrl(
  5510.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote']]
  5511.                         ['entity_view_route_path_name']
  5512.                     )
  5513.                 );
  5514.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5515.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5516.                     $StID,
  5517.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5518.                 );
  5519.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
  5520.                     $loginId,
  5521.                     $approveRole,
  5522.                     $request->request->get('approvalHash'));
  5523.                 $this->addFlash(
  5524.                     'success',
  5525.                     'Stock Consumption Added.'
  5526.                 );
  5527.                 $url $this->generateUrl(
  5528.                     'view_stock_consumption_note'
  5529.                 );
  5530.                 return $this->redirect($url "/" $StID);
  5531.             }
  5532.         }
  5533.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5534.             array(
  5535.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5536.             )
  5537.         );
  5538.         $INVLIST = [];
  5539.         foreach ($slotList as $slot) {
  5540.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5541.         }
  5542.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5543.             array(
  5544.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5545.             )
  5546.         );
  5547.         $consumptionTypeList = [];
  5548.         $consumptionTypeListArray = [];
  5549.         foreach ($consumptionTypeQry as $entry) {
  5550.             $p = array(
  5551.                 'name' => $entry->getName(),
  5552.                 'id' => $entry->getConsumptionTypeId(),
  5553.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5554.                 'cost_center_id' => $entry->getCostCenterId(),
  5555.             );
  5556.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5557.             $consumptionTypeListArray[] = $p;
  5558.         }
  5559.         //add bill list
  5560.         $service_purchase_bill_query $this->getDoctrine()
  5561.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5562.             ->findBy(
  5563.                 array(
  5564.                     'typeHash' => 'SPB',
  5565.                     'approved' => GeneralConstant::APPROVED
  5566.                 )
  5567.             );
  5568.         $service_purchase_bill_list = [];
  5569.         $service_purchase_bill_list_array = [];
  5570.         $bill = array(
  5571.             'id' => 0,
  5572.             'type' => 'SPB',
  5573.             'name' => 'New Expense',
  5574.             'text' => 'New Expense',
  5575.             'amount' => 0,
  5576.         );
  5577.         $service_purchase_bill_list[0] = $bill;
  5578.         $service_purchase_bill_list_array[] = $bill;
  5579.         foreach ($service_purchase_bill_query as $d) {
  5580.             $bill = array(
  5581.                 'id' => $d->getPurchaseInvoiceId(),
  5582.                 'type' => 'SPB',
  5583.                 'name' => $d->getDocumentHash(),
  5584.                 'text' => $d->getDocumentHash(),
  5585.                 'amount' => $d->getInvoiceAmount(),
  5586.             );
  5587.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5588.             $service_purchase_bill_list_array[] = $bill;
  5589.         }
  5590.         return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_consumption_note.html.twig',
  5591.             array(
  5592.                 'page_title' => 'Stock Consumption Note',
  5593.                 'warehouseList' => Inventory::WarehouseList($em),
  5594.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  5595.                 'consumptionTypeList' => $consumptionTypeList,
  5596.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5597.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5598.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5599.                 'warehouseActionList' => $warehouse_action_list,
  5600.                 'warehouseActionListArray' => $warehouse_action_list_array,
  5601.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  5602.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  5603.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  5604.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  5605.                 'product_list' => Inventory::ProductListDetailed($this->getDoctrine()->getManager()),
  5606.                 'prefix_list' => array(
  5607.                     [
  5608.                         'id' => 1,
  5609.                         'value' => 'GN',
  5610.                         'text' => 'GN'
  5611.                     ]
  5612.                 ),
  5613.                 'assoc_list' => array(
  5614.                     [
  5615.                         'id' => 1,
  5616.                         'value' => 1,
  5617.                         'text' => 'GN'
  5618.                     ]
  5619.                 ),
  5620.                 'INVLIST' => $INVLIST
  5621.             )
  5622.         );
  5623.     }
  5624.     public function StockConsumptionNoteListAction(Request $request)
  5625.     {
  5626.         $q $this->getDoctrine()
  5627.             ->getRepository('ApplicationBundle:StockConsumptionNote')
  5628.             ->findBy(
  5629.                 array(
  5630.                     'status' => GeneralConstant::ACTIVE,
  5631.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  5632. //                    'approved' =>  GeneralConstant::APPROVED,
  5633.                 )
  5634.             );
  5635.         $stage_list = array(
  5636.             => 'Pending',
  5637.             => 'Pending',
  5638.             => 'Complete',
  5639.             => 'Partial',
  5640.         );
  5641.         $data = [];
  5642.         foreach ($q as $entry) {
  5643.             $data[] = array(
  5644.                 'doc_date' => $entry->getStockConsumptionNoteDate(),
  5645.                 'id' => $entry->getStockConsumptionNoteId(),
  5646.                 'doc_hash' => $entry->getDocumentHash(),
  5647.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5648.                 'stage' => $stage_list[$entry->getStage()]
  5649.             );
  5650.         }
  5651.         return $this->render('ApplicationBundle:pages/inventory/view:stock_consumption_note_list.html.twig',
  5652.             array(
  5653.                 'page_title' => 'Stock Consumption Note List',
  5654.                 'data' => $data
  5655.             )
  5656.         );
  5657.     }
  5658.     public function ViewStockConsumptionNoteAction(Request $request$id)
  5659.     {
  5660.         $em $this->getDoctrine()->getManager();
  5661.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5662.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5663.             array(
  5664.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5665.             )
  5666.         );
  5667.         $consumptionTypeList = [];
  5668.         $consumptionTypeListArray = [];
  5669.         foreach ($consumptionTypeQry as $entry) {
  5670.             $p = array(
  5671.                 'name' => $entry->getName(),
  5672.                 'id' => $entry->getConsumptionTypeId(),
  5673.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5674.                 'cost_center_id' => $entry->getCostCenterId(),
  5675.             );
  5676.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5677.             $consumptionTypeListArray[] = $p;
  5678.         }
  5679.         //add bill list
  5680.         $service_purchase_bill_query $this->getDoctrine()
  5681.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5682.             ->findBy(
  5683.                 array(
  5684.                     'typeHash' => 'SPB',
  5685.                     'approved' => GeneralConstant::APPROVED
  5686.                 )
  5687.             );
  5688.         $service_purchase_bill_list = [];
  5689.         $service_purchase_bill_list_array = [];
  5690.         $bill = array(
  5691.             'id' => 0,
  5692.             'type' => 'SPB',
  5693.             'name' => 'New Expense',
  5694.             'text' => 'New Expense',
  5695.             'amount' => 0,
  5696.         );
  5697.         $service_purchase_bill_list[0] = $bill;
  5698.         $service_purchase_bill_list_array[] = $bill;
  5699.         foreach ($service_purchase_bill_query as $d) {
  5700.             $bill = array(
  5701.                 'id' => $d->getPurchaseInvoiceId(),
  5702.                 'type' => 'SPB',
  5703.                 'name' => $d->getDocumentHash(),
  5704.                 'text' => $d->getDocumentHash(),
  5705.                 'amount' => $d->getInvoiceAmount(),
  5706.             );
  5707.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5708.             $service_purchase_bill_list_array[] = $bill;
  5709.         }
  5710.         return $this->render('ApplicationBundle:pages/inventory/view:view_stock_consumption_note.html.twig',
  5711.             array(
  5712.                 'page_title' => 'Stock Transfer',
  5713.                 'data' => $dt,
  5714.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5715.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5716.                 'consumptionTypeList' => $consumptionTypeList,
  5717.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5718.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5719.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5720.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5721.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5722.                     $id,
  5723.                     $dt['created_by'],
  5724.                     $dt['edited_by'])
  5725.             )
  5726.         );
  5727.     }
  5728.     public function PrintStockConsumptionNoteAction(Request $request$id)
  5729.     {
  5730.         $em $this->getDoctrine()->getManager();
  5731.         $dt Inventory::GetStockConsumptionNoteDetails($em$id);
  5732.         $company_data Company::getCompanyData($em1);
  5733.         $document_mark = array(
  5734.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5735.             'copy' => ''
  5736.         );
  5737.         $consumptionTypeQry $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
  5738.             array(
  5739.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5740.             )
  5741.         );
  5742.         $consumptionTypeList = [];
  5743.         $consumptionTypeListArray = [];
  5744.         foreach ($consumptionTypeQry as $entry) {
  5745.             $p = array(
  5746.                 'name' => $entry->getName(),
  5747.                 'id' => $entry->getConsumptionTypeId(),
  5748.                 'accounts_head_id' => $entry->getAccountsHeadId(),
  5749.                 'cost_center_id' => $entry->getCostCenterId(),
  5750.             );
  5751.             $consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
  5752.             $consumptionTypeListArray[] = $p;
  5753.         }
  5754.         //add bill list
  5755.         $service_purchase_bill_query $this->getDoctrine()
  5756.             ->getRepository('ApplicationBundle:PurchaseInvoice')
  5757.             ->findBy(
  5758.                 array(
  5759.                     'typeHash' => 'SPB',
  5760.                     'approved' => GeneralConstant::APPROVED
  5761.                 )
  5762.             );
  5763.         $service_purchase_bill_list = [];
  5764.         $service_purchase_bill_list_array = [];
  5765.         $bill = array(
  5766.             'id' => 0,
  5767.             'type' => 'SPB',
  5768.             'name' => 'New Expense',
  5769.             'text' => 'New Expense',
  5770.             'amount' => 0,
  5771.         );
  5772.         $service_purchase_bill_list[0] = $bill;
  5773.         $service_purchase_bill_list_array[] = $bill;
  5774.         foreach ($service_purchase_bill_query as $d) {
  5775.             $bill = array(
  5776.                 'id' => $d->getPurchaseInvoiceId(),
  5777.                 'type' => 'SPB',
  5778.                 'name' => $d->getDocumentHash(),
  5779.                 'text' => $d->getDocumentHash(),
  5780.                 'amount' => $d->getInvoiceAmount(),
  5781.             );
  5782.             $service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
  5783.             $service_purchase_bill_list_array[] = $bill;
  5784.         }
  5785.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5786.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_stock_consumption_note.html.twig',
  5787.                 array(
  5788.                     //full array here
  5789.                     'pdf' => true,
  5790.                     'page_title' => 'Stock Consumption',
  5791.                     'export' => 'pdf,print',
  5792.                     'data' => $dt,
  5793.                     'service_purchase_bill_list' => $service_purchase_bill_list,
  5794.                     'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5795.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5796.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5797.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5798.                         array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5799.                         $id,
  5800.                         $dt['created_by'],
  5801.                         $dt['edited_by']),
  5802.                     'document_mark_image' => $document_mark['original'],
  5803.                     'consumptionTypeList' => $consumptionTypeList,
  5804.                     'consumptionTypeListArray' => $consumptionTypeListArray,
  5805.                     'company_name' => $company_data->getName(),
  5806.                     'company_data' => $company_data,
  5807.                     'company_address' => $company_data->getAddress(),
  5808.                     'company_image' => $company_data->getImage(),
  5809.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5810.                     'red' => 0
  5811.                 )
  5812.             );
  5813.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5814. //                'orientation' => 'landscape',
  5815. //                'enable-javascript' => true,
  5816. //                'javascript-delay' => 1000,
  5817.                 'no-stop-slow-scripts' => false,
  5818.                 'no-background' => false,
  5819.                 'lowquality' => false,
  5820.                 'encoding' => 'utf-8',
  5821. //            'images' => true,
  5822. //            'cookie' => array(),
  5823.                 'dpi' => 300,
  5824.                 'image-dpi' => 300,
  5825. //                'enable-external-links' => true,
  5826. //                'enable-internal-links' => true
  5827.             ));
  5828.             return new Response(
  5829.                 $pdf_response,
  5830.                 200,
  5831.                 array(
  5832.                     'Content-Type' => 'application/pdf',
  5833.                     'Content-Disposition' => 'attachment; filename="stock_consumption_note_' $id '.pdf"'
  5834.                 )
  5835.             );
  5836.         }
  5837.         return $this->render('ApplicationBundle:pages/inventory/print:print_stock_consumption_note.html.twig',
  5838.             array(
  5839.                 'page_title' => 'Stock Consumption',
  5840.                 'export' => 'pdf,print',
  5841.                 'data' => $dt,
  5842.                 'service_purchase_bill_list' => $service_purchase_bill_list,
  5843.                 'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
  5844.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5845.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  5846.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  5847.                     array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
  5848.                     $id,
  5849.                     $dt['created_by'],
  5850.                     $dt['edited_by']),
  5851.                 'document_mark_image' => $document_mark['original'],
  5852.                 'consumptionTypeList' => $consumptionTypeList,
  5853.                 'consumptionTypeListArray' => $consumptionTypeListArray,
  5854.                 'company_name' => $company_data->getName(),
  5855.                 'company_data' => $company_data,
  5856.                 'company_address' => $company_data->getAddress(),
  5857.                 'company_image' => $company_data->getImage(),
  5858.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5859.                 'red' => 0
  5860.             )
  5861.         );
  5862.     }
  5863.     public function CreateStockReceivedNoteAction(Request $request$id 0)
  5864.     {
  5865.         $em $this->getDoctrine()->getManager();
  5866.         $companyId $this->getLoggedUserCompanyId($request);
  5867.         $extDocData = [];
  5868.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5869.         $warehouse_action_list Inventory::warehouse_action_list($em$companyId'object');;
  5870.         $warehouse_action_list_array Inventory::warehouse_action_list($em$companyId'array');;
  5871. //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  5872.         $userBranchIdList $request->getSession()->get('branchIdList');
  5873.         if ($userBranchIdList == null$userBranchIdList = [];
  5874.         $userBranchId $request->getSession()->get('branchId');
  5875.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  5876.             $em $this->getDoctrine()->getManager();
  5877.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //change
  5878.             $dochash $request->request->get('docHash'); //change
  5879.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5880.             $approveRole $request->request->get('approvalRole');
  5881.             $approveHash $request->request->get('approvalHash');
  5882.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  5883.                 $loginId$approveRole$approveHash$id)
  5884.             ) {
  5885.                 if ($request->request->has('returnJson')) {
  5886.                     return new JsonResponse(array(
  5887.                         'success' => false,
  5888.                         'documentHash' => 0,
  5889.                         'documentId' => 0,
  5890.                         'billIds' => [],
  5891.                         'drIds' => [],
  5892.                         'pmntTransIds' => [],
  5893.                         'viewUrl' => '',
  5894.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5895.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5896.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5897.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5898.                     ));
  5899.                 } else
  5900.                     $this->addFlash(
  5901.                         'error',
  5902.                         'Sorry Could not insert Data.'
  5903.                     );
  5904.             } else {
  5905.                 if ($request->request->has('check_allowed'))
  5906.                     $check_allowed 1;
  5907.                 $StID Inventory::CreateNewStockReceivedNote(
  5908.                     $this->getDoctrine()->getManager(),
  5909.                     $request->request,
  5910.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5911.                     $this->getLoggedUserCompanyId($request)
  5912.                 );
  5913.                 //now add Approval info
  5914.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5915.                 $approveRole 1;  //created
  5916.                 $options = array(
  5917.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5918.                     'notification_server' => $this->container->getParameter('notification_server'),
  5919.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5920.                     'url' => $this->generateUrl(
  5921.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']]
  5922.                         ['entity_view_route_path_name']
  5923.                     )
  5924.                 );
  5925.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  5926.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  5927.                     $StID,
  5928.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  5929.                 );
  5930.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
  5931.                     $loginId,
  5932.                     $approveRole,
  5933.                     $request->request->get('approvalHash'));
  5934.                 $url $this->generateUrl(
  5935.                     'view_srcv'
  5936.                 );
  5937.                 if ($request->request->has('returnJson')) {
  5938.                     return new JsonResponse(array(
  5939.                         'success' => true,
  5940.                         'documentHash' => $dochash,
  5941.                         'documentId' => $StID,
  5942.                         'viewUrl' => $url "/" $StID,
  5943.                     ));
  5944.                 } else {
  5945.                     $this->addFlash(
  5946.                         'success',
  5947.                         'Stock Received Note Added.'
  5948.                     );
  5949.                     return $this->redirect($url "/" $StID);
  5950.                 }
  5951.             }
  5952.         }
  5953.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  5954.             array(
  5955.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  5956.             )
  5957.         );
  5958.         if ($id == 0) {
  5959.         } else {
  5960.             $extDoc $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  5961.                 array(
  5962.                     'salesOrderId' => $id///material
  5963.                 )
  5964.             );
  5965.             //now if its not editable, redirect to view
  5966.             if ($extDoc) {
  5967.                 if ($extDoc->getEditFlag() != 1) {
  5968.                     $url $this->generateUrl(
  5969.                         'view_srcv'
  5970.                     );
  5971.                     return $this->redirect($url "/" $id);
  5972.                 } else {
  5973.                     $extDocData $extDoc;
  5974.                     $extDocDataDetails $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
  5975.                         array(
  5976.                             'stockReceivedNoteId' => $id///material
  5977.                         )
  5978.                     );
  5979.                 }
  5980.             } else {
  5981.             }
  5982.         }
  5983.         $INVLIST = [];
  5984.         foreach ($slotList as $slot) {
  5985.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  5986.         }
  5987.         $dataArray = array(
  5988.             'page_title' => 'Stock Received Note',
  5989. //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  5990.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  5991.             'users' => Users::getUserListById($em),
  5992.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  5993.             'warehouseList' => Inventory::WarehouseList($em),
  5994.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  5995.             'warehouseActionList' => $warehouse_action_list,
  5996.             'warehouseActionListArray' => $warehouse_action_list_array,
  5997.             'extDocData' => $extDocData,
  5998.             'credit_head_list' => Accounts::getParentLedgerHeads($em'pv''', [], 1$companyId),
  5999.             'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6000.             'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6001.             'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6002. //            'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6003. //            'product_list' => Inventory::ProductList($em, $companyId),
  6004.             'salesOrderList' => SalesOrderM::SalesOrderList($em$companyId),
  6005.             'prefix_list' => array(
  6006.                 [
  6007.                     'id' => 1,
  6008.                     'value' => 'GN',
  6009.                     'text' => 'GN'
  6010.                 ]
  6011.             ),
  6012.             'assoc_list' => array(
  6013.                 [
  6014.                     'id' => 1,
  6015.                     'value' => 1,
  6016.                     'text' => 'GN'
  6017.                 ]
  6018.             ),
  6019.             'INVLIST' => $INVLIST,
  6020.             'stList' => Inventory::StockTransferList($em$companyId, [], GeneralConstant::STAGE_PENDING_TAG0),
  6021.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  6022.             'userBranchIdList' => $userBranchIdList,
  6023.             'userBranchId' => $userBranchId,
  6024. //            'headList' => Accounts::HeadList($em),
  6025.         );
  6026.         //json
  6027.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  6028.         {
  6029.             $dataArray['success'] = true;
  6030.             return new JsonResponse(
  6031.                 $dataArray
  6032.             );
  6033.         }
  6034.         return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_received_note.html.twig',
  6035.             $dataArray
  6036.         );
  6037.     }
  6038.     public function GetItemListForStockReceivedAction(Request $request)
  6039.     {
  6040.         if ($request->isMethod('POST')) {
  6041.             $em $this->getDoctrine();
  6042.             $receiveType 1;//transfer
  6043.             if ($request->request->has('receiveType'))
  6044.                 $receiveType $request->request->get('receiveType');
  6045.             $QD = [];
  6046.             if ($receiveType == 1)
  6047.                 $QD $this->getDoctrine()
  6048.                     ->getRepository('ApplicationBundle:StockTransferItem')
  6049.                     ->findBy(
  6050.                         array(
  6051. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6052.                             'stockTransferId' => $request->request->get('stId')
  6053.                         ),
  6054.                         array()
  6055.                     );
  6056.             if ($receiveType == 2)
  6057.                 $QD $this->getDoctrine()
  6058.                     ->getRepository('ApplicationBundle:SalesOrderItem')
  6059.                     ->findBy(
  6060.                         array(
  6061. //                        'CompanyId'=> $this->getLoggedUserCompanyId($request),
  6062.                             'salesOrderId' => $request->request->get('soId')
  6063.                         ),
  6064.                         array()
  6065.                     );
  6066. //            if($request->request->get('wareHouseId')!='')
  6067. //
  6068. //            $DO=$this->getDoctrine()
  6069. //                ->getRepository('ApplicationBundle:DeliveryOrder')
  6070. //                ->findOneBy(
  6071. //                    $find_array,
  6072. //                    array(
  6073. //
  6074. //                    )
  6075. //                );
  6076.             $sendData = array(
  6077. //                'salesType'=>$SO->getSalesType(),
  6078. //                'packageData'=>[],
  6079.                 'productList' => [],
  6080. //                'productListByPackage'=>[],
  6081.             );
  6082.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
  6083.             $pckg_item_cross_match_data = [];
  6084.             foreach ($QD as $product) {
  6085. //                $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  6086.                 $b_code = [];
  6087.                 if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  6088.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6089.                     if ($to_analyze_codes_str != null)
  6090.                         $b_code json_decode($to_analyze_codes_strtrue512JSON_BIGINT_AS_STRING);
  6091.                     else
  6092.                         $b_code = [];
  6093.                 } else {
  6094.                     $to_analyze_codes_str $receiveType == $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
  6095.                     if ($to_analyze_codes_str != null) {
  6096.                         $max_int_length strlen((string)PHP_INT_MAX) - 1;
  6097.                         $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$to_analyze_codes_str);
  6098.                         $b_code json_decode($json_without_bigintstrue);
  6099.                     } else {
  6100.                         $b_code = [];
  6101.                     }
  6102.                 }
  6103.                 $b_code_data = [];
  6104.                 foreach ($b_code as $d) {
  6105.                     $b_code_data[] = array(
  6106.                         'id' => $d,
  6107.                         'name' => str_pad($d13'0'STR_PAD_LEFT),
  6108.                     );
  6109.                 }
  6110.                 $p_data = array(
  6111.                     'details_id' => $product->getId(),
  6112.                     'productId' => $product->getProductId(),
  6113.                     'product_name' => $productList[$product->getProductId()]['name'],
  6114.                     'product_barcodes' => $b_code_data,
  6115. //                    'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
  6116. //                        'package_id'=>$product->getPackageId(),
  6117.                     'qty' => $receiveType == $product->getQty() : $product->getToBeReceived(),
  6118.                     'unit_price' => $receiveType == $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
  6119.                     'balance' => $receiveType == $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
  6120. //                        'delivered'=>$product->getDelivered(),
  6121.                 );
  6122.                 $sendData['productList'][] = $p_data;
  6123.             }
  6124.             //now package data
  6125.             if ($sendData) {
  6126.                 return new JsonResponse(array("success" => true"content" => $sendData));
  6127.             }
  6128.             return new JsonResponse(array("success" => false));
  6129.         }
  6130.         return new JsonResponse(array("success" => false));
  6131.     }
  6132.     public function StockReceivedNoteListAction(Request $request)
  6133.     {
  6134.         $q $this->getDoctrine()
  6135.             ->getRepository('ApplicationBundle:StockReceivedNote')
  6136.             ->findBy(
  6137.                 array(
  6138.                     'status' => GeneralConstant::ACTIVE,
  6139.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  6140. //                    'approved' =>  GeneralConstant::APPROVED,
  6141.                 )
  6142.             );
  6143.         $stage_list = array(
  6144.             => 'Pending',
  6145.             => 'Pending',
  6146.             => 'Complete',
  6147.             => 'Partial',
  6148.         );
  6149.         $data = [];
  6150.         foreach ($q as $entry) {
  6151.             $data[] = array(
  6152.                 'doc_date' => $entry->getStockReceivedNoteDate(),
  6153.                 'id' => $entry->getStockReceivedNoteId(),
  6154.                 'doc_hash' => $entry->getDocumentHash(),
  6155.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  6156.                 'stage' => $stage_list[$entry->getStage()]
  6157.             );
  6158.         }
  6159.         return $this->render('ApplicationBundle:pages/inventory/view:stock_received_note_list.html.twig',
  6160.             array(
  6161.                 'page_title' => 'Stock Received List',
  6162.                 'data' => $data
  6163.             )
  6164.         );
  6165.     }
  6166.     public function ViewStockReceivedNoteAction(Request $request$id)
  6167.     {
  6168.         $em $this->getDoctrine()->getManager();
  6169.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6170.         return $this->render('ApplicationBundle:pages/inventory/view:view_stock_received_note.html.twig',
  6171.             array(
  6172.                 'page_title' => 'Stock Received Note',
  6173.                 'data' => $dt,
  6174.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  6175.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6176.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6177.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6178.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6179.                     $id,
  6180.                     $dt['created_by'],
  6181.                     $dt['edited_by'])
  6182.             )
  6183.         );
  6184.     }
  6185.     public function PrintStockReceivedNoteAction(Request $request$id)
  6186.     {
  6187.         $em $this->getDoctrine()->getManager();
  6188.         $dt Inventory::GetStockReceivedNoteDetails($em$id);
  6189.         $company_data Company::getCompanyData($em1);
  6190.         $document_mark = array(
  6191.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6192.             'copy' => ''
  6193.         );
  6194.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6195.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_stock_received_note.html.twig',
  6196.                 array(
  6197.                     //full array here
  6198.                     'pdf' => true,
  6199.                     'page_title' => 'Stock Received Note',
  6200.                     'export' => 'pdf,print',
  6201.                     'data' => $dt,
  6202.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6203.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6204.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6205.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6206.                         $id,
  6207.                         $dt['created_by'],
  6208.                         $dt['edited_by']),
  6209.                     'document_mark_image' => $document_mark['original'],
  6210.                     'company_name' => $company_data->getName(),
  6211.                     'company_data' => $company_data,
  6212.                     'company_address' => $company_data->getAddress(),
  6213.                     'company_image' => $company_data->getImage(),
  6214.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6215.                     'red' => 0
  6216.                 )
  6217.             );
  6218.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6219. //                'orientation' => 'landscape',
  6220. //                'enable-javascript' => true,
  6221. //                'javascript-delay' => 1000,
  6222.                 'no-stop-slow-scripts' => false,
  6223.                 'no-background' => false,
  6224.                 'lowquality' => false,
  6225.                 'encoding' => 'utf-8',
  6226. //            'images' => true,
  6227. //            'cookie' => array(),
  6228.                 'dpi' => 300,
  6229.                 'image-dpi' => 300,
  6230. //                'enable-external-links' => true,
  6231. //                'enable-internal-links' => true
  6232.             ));
  6233.             return new Response(
  6234.                 $pdf_response,
  6235.                 200,
  6236.                 array(
  6237.                     'Content-Type' => 'application/pdf',
  6238.                     'Content-Disposition' => 'attachment; filename="stock_received_note_' $id '.pdf"'
  6239.                 )
  6240.             );
  6241.         }
  6242.         return $this->render('ApplicationBundle:pages/inventory/print:print_stock_received_note.html.twig',
  6243.             array(
  6244.                 'page_title' => 'Stock Received Note',
  6245.                 'export' => 'pdf,print',
  6246.                 'data' => $dt,
  6247.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6248.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  6249.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  6250.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  6251.                     $id,
  6252.                     $dt['created_by'],
  6253.                     $dt['edited_by']),
  6254.                 'document_mark_image' => $document_mark['original'],
  6255.                 'company_name' => $company_data->getName(),
  6256.                 'company_data' => $company_data,
  6257.                 'company_address' => $company_data->getAddress(),
  6258.                 'company_image' => $company_data->getImage(),
  6259.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  6260.                 'red' => 0
  6261.             )
  6262.         );
  6263.     }
  6264.     public function CreateStoreRequisitionSlipAction(Request $request$id 0)
  6265.     {
  6266.         $em $this->getDoctrine()->getManager();
  6267. //        $id;
  6268.         if ($request->isMethod('POST')) {
  6269.             $em $this->getDoctrine()->getManager();
  6270.             $entity_id array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //change
  6271.             $dochash $request->request->get('voucherNumber'); //change
  6272.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6273.             $approveRole $request->request->get('approvalRole');
  6274.             $approveHash $request->request->get('approvalHash');
  6275.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6276.                 $loginId$approveRole$approveHash$id)
  6277.             ) {
  6278.                 $this->addFlash(
  6279.                     'error',
  6280.                     'Sorry, could not insert Data.'
  6281.                 );
  6282.             } else {
  6283.                 if ($request->request->has('check_allowed'))
  6284.                     $check_allowed 1;
  6285.                 $IrID Inventory::CreateNewStoreRequisition($id,
  6286.                     $this->getDoctrine()->getManager(),
  6287.                     $request->request,
  6288.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6289.                     $this->getLoggedUserCompanyId($request)
  6290.                 );
  6291.                 //now add Approval info
  6292.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6293.                 $approveRole $request->request->get('approvalRole');
  6294.                 $options = array(
  6295.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6296.                     'notification_server' => $this->container->getParameter('notification_server'),
  6297.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6298.                     'url' => $this->generateUrl(
  6299.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StoreRequisition']]
  6300.                         ['entity_view_route_path_name']
  6301.                     )
  6302.                 );
  6303.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6304.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  6305.                     $IrID,
  6306.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6307.                 );
  6308.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
  6309.                     $loginId,
  6310.                     $approveRole,
  6311.                     $request->request->get('approvalHash'));
  6312.                 $this->addFlash(
  6313.                     'success',
  6314.                     'New Indent Added.'
  6315.                 );
  6316.                 $url $this->generateUrl(
  6317.                     'view_ir'
  6318.                 );
  6319.                 return $this->redirect($url "/" $IrID);
  6320.             }
  6321.         }
  6322.         $extDocData = [];
  6323.         $extDocDetailsData = [];
  6324.         if ($id == 0) {
  6325.         } else {
  6326.             $extDoc $em->getRepository('ApplicationBundle:StoreRequisition')->findOneBy(
  6327.                 array(
  6328.                     'storeRequisitionId' => $id///material
  6329.                 )
  6330.             );
  6331.             //now if its not editable, redirect to view
  6332.             if ($extDoc) {
  6333.                 if ($extDoc->getEditFlag() != 1) {
  6334.                     $url $this->generateUrl(
  6335.                         'view_ir'
  6336.                     );
  6337.                     return $this->redirect($url "/" $id);
  6338.                 } else {
  6339.                     $extDocData $extDoc;
  6340.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StoreRequisitionItem')->findBy(
  6341.                         array(
  6342.                             'storeRequisitionId' => $id///material
  6343.                         )
  6344.                     );;
  6345.                 }
  6346.             } else {
  6347.             }
  6348.         }
  6349.         $companyId $this->getLoggedUserCompanyId($request);
  6350.         $productListArray = [];
  6351.         $subCategoryListArray = [];
  6352.         $categoryListArray = [];
  6353.         $igListArray = [];
  6354.         $unitListArray = [];
  6355.         $brandListArray = [];
  6356.         $productList Inventory::ProductList($em$companyId);
  6357.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6358.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6359.         $igList Inventory::ItemGroupList($em$companyId);
  6360.         $unitList Inventory::UnitTypeList($em);
  6361.         $brandList Inventory::GetBrandList($em$companyId);
  6362.         foreach ($productList as $product$productListArray[] = $product;
  6363.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6364.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6365.         foreach ($igList as $product$igListArray[] = $product;
  6366.         foreach ($unitList as $product$unitListArray[] = $product;
  6367.         foreach ($brandList as $product$brandListArray[] = $product;
  6368.         $sr_list = [];
  6369.         $QD $this->getDoctrine()
  6370.             ->getRepository('ApplicationBundle:StockRequisition')
  6371.             ->findBy(
  6372.                 array(
  6373.                     'indentTagged' => 0,
  6374.                     'approved' => 1
  6375.                 )
  6376.             );
  6377.         foreach ($QD as $dt) {
  6378.             $sr_list[$dt->getStockRequisitionId()] = array(
  6379.                 'id' => $dt->getStockRequisitionId(),
  6380.                 'name' => $dt->getDocumentHash(),
  6381.                 'text' => $dt->getDocumentHash(),
  6382.             );
  6383.         }
  6384.         return $this->render('ApplicationBundle:pages/inventory/input_forms:store_requisition.html.twig',
  6385.             array(
  6386.                 'page_title' => 'Indent Requisition Slip',
  6387.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6388.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6389.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6390.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6391.                 'sr_list' => $sr_list,
  6392.                 'productList' => $productList,
  6393.                 'subCategoryList' => $subCategoryList,
  6394.                 'categoryList' => $categoryList,
  6395.                 'igList' => $igList,
  6396.                 'extId' => $id,
  6397.                 'extDocDetailsData' => $extDocDetailsData,
  6398.                 'extDocData' => $extDocData,
  6399.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6400.                 'unitList' => $unitList,
  6401.                 'brandList' => $brandList,
  6402.                 'brandListArray' => $brandListArray,
  6403.                 'productListArray' => $productListArray,
  6404.                 'subCategoryListArray' => $subCategoryListArray,
  6405.                 'categoryListArray' => $categoryListArray,
  6406.                 'igListArray' => $igListArray,
  6407.                 'unitListArray' => $unitListArray,
  6408.                 'prefix_list' => array(
  6409.                     [
  6410.                         'id' => 1,
  6411.                         'value' => 'GN',
  6412.                         'text' => 'General'
  6413.                     ],
  6414.                     [
  6415.                         'id' => 1,
  6416.                         'value' => 'SD',
  6417.                         'text' => 'For Sales Demand'
  6418.                     ]
  6419.                 ),
  6420.                 'assoc_list' => array(
  6421.                     [
  6422.                         'id' => 1,
  6423.                         'value' => 1,
  6424.                         'text' => 'GN'
  6425.                     ]
  6426.                 )
  6427.             )
  6428.         );
  6429.     }
  6430.     public function CreateStockRequisitionSlipAction(Request $request$id 0)
  6431.     {
  6432.         $em $this->getDoctrine()->getManager();
  6433.         if ($request->isMethod('POST')) {
  6434.             $em $this->getDoctrine()->getManager();
  6435.             $entity_id array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //change
  6436.             $dochash $request->request->get('voucherNumber'); //change
  6437.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6438.             $approveRole $request->request->get('approvalRole');
  6439.             $approveHash $request->request->get('approvalHash');
  6440.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  6441.                 $loginId$approveRole$approveHash$id)
  6442.             ) {
  6443.                 $this->addFlash(
  6444.                     'error',
  6445.                     'Sorry, could not insert Data.'
  6446.                 );
  6447.             } else {
  6448.                 if ($request->request->has('check_allowed'))
  6449.                     $check_allowed 1;
  6450.                 $SrID Inventory::CreateNewStockRequisition($id,
  6451.                     $this->getDoctrine()->getManager(),
  6452.                     $request->request,
  6453.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6454.                     $this->getLoggedUserCompanyId($request)
  6455.                 );
  6456.                 //now add Approval info
  6457.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6458.                 $approveRole $request->request->get('approvalRole');
  6459.                 $options = array(
  6460.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  6461.                     'notification_server' => $this->container->getParameter('notification_server'),
  6462.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  6463.                     'url' => $this->generateUrl(
  6464.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['StockRequisition']]
  6465.                         ['entity_view_route_path_name']
  6466.                     )
  6467.                 );
  6468.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  6469.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  6470.                     $SrID,
  6471.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  6472.                 );
  6473.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
  6474.                     $loginId,
  6475.                     $approveRole,
  6476.                     $request->request->get('approvalHash'));
  6477.                 $this->addFlash(
  6478.                     'success',
  6479.                     'New Requisition Added.'
  6480.                 );
  6481.                 $url $this->generateUrl(
  6482.                     'view_sr'
  6483.                 );
  6484. //                return $this->redirect($url . "/" . $SrID);
  6485.             }
  6486.         }
  6487.         $extDocData = [];
  6488.         $extDocDetailsData = [];
  6489.         if ($id == 0) {
  6490.         } else {
  6491.             $extDoc $em->getRepository('ApplicationBundle:StockRequisition')->findOneBy(
  6492.                 array(
  6493.                     'stockRequisitionId' => $id///material
  6494.                 )
  6495.             );
  6496.             //now if its not editable, redirect to view
  6497.             if ($extDoc) {
  6498.                 if ($extDoc->getEditFlag() != 1) {
  6499.                     $url $this->generateUrl(
  6500.                         'view_sr'
  6501.                     );
  6502.                     return $this->redirect($url "/" $id);
  6503.                 } else {
  6504.                     $extDocData $extDoc;
  6505.                     $extDocDetailsData $em->getRepository('ApplicationBundle:StockRequisitionItem')->findBy(
  6506.                         array(
  6507.                             'stockRequisitionId' => $id///material
  6508.                         )
  6509.                     );;
  6510.                 }
  6511.             } else {
  6512.             }
  6513.         }
  6514.         $companyId $this->getLoggedUserCompanyId($request);
  6515.         $productListArray = [];
  6516.         $subCategoryListArray = [];
  6517.         $categoryListArray = [];
  6518.         $igListArray = [];
  6519.         $unitListArray = [];
  6520.         $brandListArray = [];
  6521.         $productList Inventory::ProductList($em$companyId);
  6522.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  6523.         $categoryList Inventory::ProductCategoryList($em$companyId);
  6524.         $igList Inventory::ItemGroupList($em$companyId);
  6525.         $unitList Inventory::UnitTypeList($em);
  6526.         $brandList Inventory::GetBrandList($em$companyId);
  6527.         foreach ($productList as $product$productListArray[] = $product;
  6528.         foreach ($categoryList as $product$categoryListArray[] = $product;
  6529.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  6530.         foreach ($igList as $product$igListArray[] = $product;
  6531.         foreach ($unitList as $product$unitListArray[] = $product;
  6532.         foreach ($brandList as $product$brandListArray[] = $product;
  6533.         return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_requisition_slip.html.twig',
  6534.             array(
  6535.                 'page_title' => 'Stock Requisition Slip',
  6536.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6537.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  6538.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  6539.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  6540.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  6541.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  6542.                 'productList' => $productList,
  6543.                 'extId' => $id,
  6544.                 'extDocDetailsData' => $extDocDetailsData,
  6545.                 'extDocData' => $extDocData,
  6546.                 'subCategoryList' => $subCategoryList,
  6547.                 'categoryList' => $categoryList,
  6548.                 'igList' => $igList,
  6549.                 'unitList' => $unitList,
  6550.                 'brandList' => $brandList,
  6551.                 'brandListArray' => $brandListArray,
  6552.                 'productListArray' => $productListArray,
  6553.                 'subCategoryListArray' => $subCategoryListArray,
  6554.                 'categoryListArray' => $categoryListArray,
  6555.                 'igListArray' => $igListArray,
  6556.                 'unitListArray' => $unitListArray,
  6557.                 'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6558.                 'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6559.                 'prefix_list' => array(
  6560.                     [
  6561.                         'id' => 1,
  6562.                         'value' => 'GN',
  6563.                         'text' => 'General'
  6564.                     ],
  6565.                     [
  6566.                         'id' => 1,
  6567.                         'value' => 'SD',
  6568.                         'text' => 'For Sales Demand'
  6569.                     ]
  6570.                 ),
  6571.                 'projectList' => $em->getRepository('ApplicationBundle:Project')->findBy(
  6572.                     array(
  6573.                         'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  6574.                     ), array('projectDate' => 'desc')
  6575.                 ),
  6576.                 'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
  6577.                 'assoc_list' => array(
  6578.                     [
  6579.                         'id' => 1,
  6580.                         'value' => 'GN',
  6581.                         'text' => 'General'
  6582.                     ]
  6583.                 )
  6584.             )
  6585.         );
  6586.     }
  6587.     public function CreateStockReturnAction(Request $request)
  6588.     {
  6589.         return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_return.html.twig',
  6590.             array(
  6591.                 'page_title' => 'Stock Return',
  6592. //                'dataList'=>$dta_list
  6593.             )
  6594.         );
  6595.     }
  6596.     public function MaterialInwardAction(Request $request)
  6597.     {
  6598.         $data = [];
  6599.         if ($request->isMethod('POST')) {
  6600.             //first of all resolve the transport costs
  6601.             $total_price_value 0;
  6602.             $data_list $dt $this->getDoctrine()
  6603.                 ->getRepository('ApplicationBundle:PurchaseOrderItem')
  6604.                 ->findBy(
  6605.                     array(
  6606.                         'purchaseOrderId' => $request->request->get('poId'),
  6607.                         'productId' => $request->request->get('products')
  6608.                     )
  6609.                 );
  6610.             $purchase_items = [];
  6611.             foreach ($data_list as $key => $value) {
  6612.                 $purchase_items[$value->getProductId()] = $value;
  6613.             }
  6614.             foreach ($request->request->get('products') as $key => $entry) {
  6615.                 $total_price_value $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
  6616.             }
  6617.             $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
  6618.             $supplier_id $po_data['supplier_id'];
  6619.             $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6620.             foreach ($request->request->get('products') as $key => $entry) {
  6621.                 if ($request->request->get('receivedQty')[$key] > 0)
  6622.                     Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
  6623.                         $request->request,
  6624.                         $key,
  6625.                         $request->request->get('poId'),
  6626.                         $request->request->get('purchaseOrderItemId'),
  6627.                         $supplier_id,
  6628.                         $request->request->get('warehouseId'),
  6629.                         $request->request->get('lotNumber'),
  6630.                         $request->request->get('type_hash'),
  6631.                         $request->request->get('prefix_hash'),
  6632.                         $request->request->get('assoc_hash'),
  6633.                         $request->request->get('number_hash'),
  6634.                         $request->request->get('docHash'),
  6635.                         $request->request->get('docDate'),
  6636.                         $purchase_items[$entry],
  6637.                         $total_price_value,
  6638.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6639.             }
  6640.             $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
  6641. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6642.             System::AddNewNotification($this->container->getParameter('notification_enabled'), $this->container->getParameter('notification_server'), $request->getSession()->get(UserConstants::USER_APP_ID), $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6643.                 "A stack of material Has Arrived at The " $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6644.                 'all',
  6645.                 "",
  6646.                 'information',
  6647.                 "",
  6648.                 "Inbound Material"
  6649.             );
  6650. //                System::AddNewNotification(                     $this->container->getParameter('notification_enabled'),                     $this->container->getParameter('notification_server'),$request->getSession()->get(UserConstants::USER_APP_ID),$request->getSession()->get(UserConstants::USER_COMPANY_ID),"Eco is the best",'all','','success',null);
  6651.         }
  6652.         return $this->render('ApplicationBundle:pages/inventory/input_forms:material_inward.html.twig',
  6653.             array(
  6654.                 'page_title' => 'Material Inward',
  6655.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6656.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6657.                 'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
  6658.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6659.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6660.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6661.                 "unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
  6662. //                'po'=>Inventory::getPurchaseOrderList
  6663.             )
  6664.         );
  6665.     }
  6666.     public function QualityControlAction(Request $request)
  6667.     {
  6668.         $checked_qc_list_flag 0;
  6669.         if ($request->query->has('checked_qc_list_flag'))
  6670.             $checked_qc_list_flag $request->query->has('checked_qc_list_flag');
  6671.         if ($request->isMethod('POST')) {
  6672.             foreach ($request->request->get('qc_checked', []) as $key => $entry) {
  6673.                 $em $this->getDoctrine()->getManager();
  6674.                 $data $this->getDoctrine()
  6675.                     ->getRepository('ApplicationBundle:MaterialInward')
  6676.                     ->findOneBy(
  6677.                         array(
  6678.                             'qcId' => $entry
  6679.                         )
  6680.                     );
  6681.                 if ($request->request->get('approvedQty')[$entry] <= 0) {
  6682.                     $em->remove($data);
  6683.                     $em->flush();
  6684.                 } else {
  6685.                     $data->setApprovedQty($request->request->get('approvedQty')[$entry]);
  6686.                     $data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
  6687.                     $data->setQcDate(new \DateTime($request->request->get('qcDate')));
  6688.                     $data->setStage(GeneralConstant::STAGE_PENDING_TAG);
  6689.                     $em->flush();
  6690.                 }
  6691.                 //notification
  6692.                 $po_data Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
  6693.                 $supplier_id $po_data['supplier_id'];
  6694.                 $supplier_name Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
  6695.                 $product_name Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
  6696.                 $qty $request->request->get('approvedQty')[$entry];
  6697.                 $warehouse_name Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
  6698. //            $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
  6699.                 System::AddNewNotification($this->container->getParameter('notification_enabled'), $this->container->getParameter('notification_server'), $request->getSession()->get(UserConstants::USER_APP_ID), $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  6700.                     $qty " among " $data->getInwardQty() . " units of " $product_name " has passed the Quality Control in " .
  6701.                     $warehouse_name " From Supplier: " $supplier_name ". The P/O number is  " $po_data['name'] . " .",
  6702.                     'all',
  6703.                     "",
  6704.                     'success',
  6705.                     "",
  6706.                     "Quality Control"
  6707.                 );
  6708.             }
  6709.         }
  6710.         return $this->render('ApplicationBundle:pages/inventory/input_forms:qc.html.twig',
  6711.             array(
  6712.                 'page_title' => 'Quality Control',
  6713.                 'checked_qc_list_flag' => $checked_qc_list_flag,
  6714.                 'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
  6715.                 'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6716.                 'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
  6717.                 'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
  6718.                 'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
  6719.                 'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
  6720.                 'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6721.                 'material_inward' => $this->getDoctrine()
  6722.                     ->getRepository('ApplicationBundle:MaterialInward')
  6723.                     ->findBy(
  6724.                         array(
  6725.                             'stage' => $checked_qc_list_flag == GeneralConstant::STAGE_PENDING GeneralConstant::STAGE_PENDING_TAG
  6726.                         )
  6727.                     )
  6728. //                'po'=>Inventory::getPurchaseOrderList
  6729.             )
  6730.         );
  6731.     }
  6732.     public function InventoryTransactionViewAction(Request $request)
  6733.     {
  6734.         $em $this->getDoctrine()->getManager();
  6735.         $qry_data = array(
  6736.             'warehouseId' => [0],
  6737.             'igId' => [0],
  6738.             'brandId' => [0],
  6739.             'categoryId' => [0],
  6740.             'actionTagId' => [0],
  6741.         );
  6742.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6743.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6744.         $data_searched = [];
  6745.         $em $this->getDoctrine()->getManager();
  6746.         $companyId $this->getLoggedUserCompanyId($request);
  6747.         $company_data Company::getCompanyData($em$companyId);
  6748.         $data = [];
  6749.         $print_title "Inventory Report";
  6750.         $document_mark = array(
  6751.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6752.             'copy' => ''
  6753.         );
  6754.         if ($request->isMethod('POST'))
  6755.             $method 'POST';
  6756.         else
  6757.             $method 'GET';
  6758.         {
  6759.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  6760.                 $request->request$method,
  6761.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6762.                 $companyId);
  6763.             if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
  6764.                 return new JsonResponse(
  6765.                     array(
  6766.                         'success' => true,
  6767. //                    'page_title' => 'Product Details',
  6768. //                    'company_data' => $company_data,
  6769.                         'page_title' => 'Inventory Transactions',
  6770.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6771.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6772.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6773.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6774.                         'data_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6775.                         'action_tag' => $warehouse_action_list,
  6776.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6777.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6778.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6779.                         'data_searched' => $data_searched
  6780.                     )
  6781.                 );
  6782.             } else if ($request->request->get('print_data_enabled') == 1) {
  6783.                 $print_sub_title "";
  6784.                 return $this->render('ApplicationBundle:pages/inventory/print:print_inventory_data.html.twig',
  6785.                     array(
  6786.                         'page_title' => 'Inventory Report',
  6787.                         'page_header' => 'Report',
  6788.                         'print_title' => $print_title,
  6789.                         'document_type' => 'Journal voucher',
  6790.                         'document_mark_image' => $document_mark['original'],
  6791.                         'page_header_sub' => 'Add',
  6792.                         'item_data' => [],
  6793.                         'received' => 2,
  6794.                         'return' => 1,
  6795.                         'total_w_vat' => 1,
  6796.                         'total_vat' => 1,
  6797.                         'total_wo_vat' => 1,
  6798.                         'invoice_id' => 'abcd1234',
  6799.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6800.                         'created_by' => 'created by',
  6801.                         'created_at' => '',
  6802.                         'red' => 0,
  6803.                         'company_name' => $company_data->getName(),
  6804.                         'company_data' => $company_data,
  6805.                         'company_address' => $company_data->getAddress(),
  6806.                         'company_image' => $company_data->getImage(),
  6807.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6808.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6809.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6810.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6811.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6812.                         'action_tag' => $warehouse_action_list,
  6813.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6814.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6815.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6816.                         'data_searched' => $data_searched
  6817.                     )
  6818.                 );
  6819.             }
  6820.         }
  6821.         return $this->render('ApplicationBundle:pages/inventory/report:inventory_transaction_view.html.twig',
  6822.             array(
  6823.                 'page_title' => 'Inventory Transactions',
  6824.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6825.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6826.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6827.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6828.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6829.                 'action_tag' => $warehouse_action_list,
  6830.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6831.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6832.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6833.                 'data_searched' => $data_searched
  6834.             )
  6835.         );
  6836.     }
  6837.     public function StockConsumptionViewAction(Request $request)
  6838.     {
  6839.         $em $this->getDoctrine()->getManager();
  6840.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  6841.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  6842.         $qry_data = array(
  6843.             'warehouseId' => [0],
  6844.             'igId' => [0],
  6845.             'brandId' => [0],
  6846.             'categoryId' => [0],
  6847.             'actionTagId' => [0],
  6848.         );
  6849.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  6850.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  6851.         $data_searched = [];
  6852.         $em $this->getDoctrine()->getManager();
  6853.         $company_data Company::getCompanyData($em1);
  6854.         $data = [];
  6855.         $print_title "Inventory Report";
  6856.         $document_mark = array(
  6857.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  6858.             'copy' => ''
  6859.         );
  6860.         if ($request->isMethod('POST'))
  6861.             $method 'POST';
  6862.         else
  6863.             $method 'GET';
  6864.         $post_data $method == 'POST' $request->request $request->query;
  6865.         $data_searched Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
  6866.             $post_data,
  6867.             $method,
  6868.             $start_date,
  6869.             $end_date,
  6870.             $request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6871.         if ($post_data->get('print_data_enabled') == 1) {
  6872.             $print_sub_title "";
  6873.             if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  6874.                 $html $this->renderView('ApplicationBundle:pages/inventory/print:print_stock_consumption.html.twig',
  6875.                     array(
  6876.                         'pdf' => 'true',
  6877.                         'page_title' => 'Inventory Report',
  6878.                         'page_header' => 'Report',
  6879.                         'print_title' => $print_title,
  6880.                         'document_type' => 'Journal voucher',
  6881.                         'document_mark_image' => $document_mark['original'],
  6882.                         'page_header_sub' => 'Add',
  6883.                         'item_data' => [],
  6884.                         'received' => 2,
  6885.                         'return' => 1,
  6886.                         'total_w_vat' => 1,
  6887.                         'total_vat' => 1,
  6888.                         'total_wo_vat' => 1,
  6889.                         'invoice_id' => 'abcd1234',
  6890.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  6891.                         'created_by' => 'created by',
  6892.                         'created_at' => '',
  6893.                         'red' => 0,
  6894.                         'start_date' => $start_date,
  6895.                         'end_date' => $end_date,
  6896.                         'openFilter' => empty($post_data->keys()) ? 0,
  6897.                         'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6898.                         'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6899.                         'company_name' => $company_data->getName(),
  6900.                         'company_data' => $company_data,
  6901.                         'company_address' => $company_data->getAddress(),
  6902.                         'company_image' => $company_data->getImage(),
  6903.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6904.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6905.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6906.                         'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6907.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6908.                         'action_tag' => $warehouse_action_list,
  6909.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6910.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6911.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6912.                         'data_searched' => $data_searched,
  6913.                         'export' => 'all'
  6914.                     )
  6915.                 );
  6916.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  6917.                     'orientation' => count($data_searched['query_columns_filter']) > 'landscape' 'portrait',
  6918.                     'no-stop-slow-scripts' => true,
  6919.                     'no-background' => false,
  6920.                     'lowquality' => false,
  6921.                     'encoding' => 'utf-8',
  6922.                     'dpi' => 300,
  6923.                     'image-dpi' => 300,
  6924.                 ));
  6925.                 return new Response(
  6926.                     $pdf_response,
  6927.                     200,
  6928.                     array(
  6929.                         'Content-Type' => 'application/pdf',
  6930.                         'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
  6931.                     )
  6932.                 );
  6933.             }
  6934.             return $this->render('ApplicationBundle:pages/inventory/print:print_stock_consumption.html.twig',
  6935.                 array(
  6936.                     'page_title' => 'Inventory Report',
  6937.                     'page_header' => 'Report',
  6938.                     'print_title' => $print_title,
  6939.                     'document_type' => 'Journal voucher',
  6940.                     'document_mark_image' => $document_mark['original'],
  6941.                     'page_header_sub' => 'Add',
  6942.                     'item_data' => [],
  6943.                     'received' => 2,
  6944.                     'return' => 1,
  6945.                     'total_w_vat' => 1,
  6946.                     'total_vat' => 1,
  6947.                     'total_wo_vat' => 1,
  6948.                     'invoice_id' => 'abcd1234',
  6949.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  6950.                     'created_by' => 'created by',
  6951.                     'created_at' => '',
  6952.                     'red' => 0,
  6953.                     'start_date' => $start_date,
  6954.                     'end_date' => $end_date,
  6955.                     'openFilter' => empty($post_data->keys()) ? 0,
  6956.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6957.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6958.                     'company_name' => $company_data->getName(),
  6959.                     'company_data' => $company_data,
  6960.                     'company_address' => $company_data->getAddress(),
  6961.                     'company_image' => $company_data->getImage(),
  6962.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6963.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6964.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6965.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6966.                     'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6967.                     'action_tag' => $warehouse_action_list,
  6968.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6969.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6970.                     'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6971.                     'data_searched' => $data_searched,
  6972.                     'export' => 'all'
  6973.                 )
  6974.             );
  6975.         }
  6976.         return $this->render('ApplicationBundle:pages/inventory/report:stock_consumption.html.twig',
  6977.             array(
  6978.                 'page_title' => 'Stock Consumption',
  6979.                 'start_date' => $start_date,
  6980.                 'end_date' => $end_date,
  6981.                 'openFilter' => empty($post_data->keys()) ? 0,
  6982.                 'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  6983.                 'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  6984.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  6985.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  6986.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  6987.                 'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  6988.                 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  6989.                 'action_tag' => $warehouse_action_list,
  6990.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  6991.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  6992.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  6993.                 'data_searched' => $data_searched
  6994.             )
  6995.         );
  6996.     }
  6997.     public function ItemViewAction(Request $request)
  6998.     {
  6999.         return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_return.html.twig',
  7000.             array(
  7001.                 'page_title' => 'Stock Return'
  7002.             )
  7003.         );
  7004.     }
  7005.     public function ProductViewAction(Request $request$id 0)
  7006.     {
  7007.         $em $this->getDoctrine()->getManager();
  7008.         $companyId $this->getLoggedUserCompanyId($request);
  7009.         $company_data Company::getCompanyData($em$companyId);
  7010.         $data = [];
  7011.         $productData $em->getRepository('ApplicationBundle:InvProducts')
  7012.             ->findOneBy(
  7013.                 array(
  7014.                     'id' => $id
  7015.                 )
  7016.             );
  7017.         $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  7018.             ->findBy(
  7019.                 array(
  7020.                     'productId' => $id
  7021.                 )
  7022.             );
  7023.         $trans_history $em->getRepository('ApplicationBundle:InvItemTransaction')
  7024.             ->findBy(
  7025.                 array(
  7026.                     'productId' => $id
  7027.                 ), array(
  7028.                     'transactionDate' => 'ASC',
  7029.                     'id' => 'ASC'
  7030.                 )
  7031.             );
  7032.         $productDataObj = array();
  7033.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  7034.             $getters array_filter(get_class_methods($productData), function ($method) {
  7035.                 return 'get' === substr($method03);
  7036.             });
  7037.             foreach ($getters as $getter) {
  7038.                 if ($getter == 'getGlobalId')
  7039.                     continue;
  7040. //                    if ($getter == 'getId')
  7041. //                        continue;
  7042.                 $Fieldname str_replace('get'''$getter);
  7043.                 $productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
  7044.             }
  7045.             if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
  7046.                 $dataArray = array(
  7047.                     'success' => true,
  7048.                     'page_title' => 'Product Details',
  7049.                     'company_data' => $company_data,
  7050.                     'productData' => $productData,
  7051.                     'productDataObj' => $productDataObj,
  7052.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7053.                 );
  7054.             } else {
  7055.                 $dataArray = array(
  7056.                     'success' => true,
  7057.                     'page_title' => 'Product Details',
  7058.                     'company_data' => $company_data,
  7059.                     'productData' => $productData,
  7060.                     'productDataObj' => $productDataObj,
  7061.                     'currInvList' => $currInvList,
  7062.                     'trans_history' => $trans_history,
  7063.                     'entityList' => GeneralConstant::$Entity_list_details,
  7064. //                    'productList' => Inventory::ProductList($em, $companyId),
  7065.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7066.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7067.                     'igList' => Inventory::ItemGroupList($em$companyId),
  7068.                     'unitList' => Inventory::UnitTypeList($em),
  7069.                     'brandList' => Inventory::GetBrandList($em$companyId),
  7070.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7071.                     'warehouseList' => Inventory::WarehouseList($em),
  7072.                     'defaultImageAppendUrl' => '/uploads/Products/',
  7073.                 );
  7074.             }
  7075.             return new JsonResponse(
  7076.                 $dataArray
  7077.             );
  7078.         }
  7079.         $dataArray = array(
  7080.             'page_title' => 'Product Details',
  7081.             'company_data' => $company_data,
  7082.             'productData' => $productData,
  7083.             'currInvList' => $currInvList,
  7084.             'trans_history' => $trans_history,
  7085.             'entityList' => GeneralConstant::$Entity_list_details,
  7086. //            'productList' => Inventory::ProductList($em, $companyId),
  7087.             'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  7088.             'categoryList' => Inventory::ProductCategoryList($em$companyId),
  7089.             'igList' => Inventory::ItemGroupList($em$companyId),
  7090.             'unitList' => Inventory::UnitTypeList($em),
  7091.             'brandList' => Inventory::GetBrandList($em$companyId),
  7092.             'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  7093.             'warehouseList' => Inventory::WarehouseList($em),
  7094.         );
  7095.         return $this->render('ApplicationBundle:pages/inventory/view:product_view.html.twig'$dataArray
  7096.         );
  7097.     }
  7098.     public function CheckForProductInWarehouseAction(Request $request$queryStr '')
  7099.     {
  7100.         $em $this->getDoctrine()->getManager();
  7101.         $companyId $this->getLoggedUserCompanyId($request);
  7102.         $data = [
  7103.             'availableQty' => 0,
  7104.             'productByCodesArray' => [],
  7105.             'indRowId' => 0
  7106.         ];
  7107.         $html '';
  7108.         $productByCodeData = [];
  7109.         if ($request->isMethod('POST')) {
  7110.             $warehouseId $request->request->get('warehouseId'0);
  7111.             $warehouseActionId $request->request->get('warehouseActionId'0);
  7112.             $productId $request->request->get('productId'0);
  7113.             $indRowId $request->request->get('indRowId'0);
  7114.             $data['indRowId'] = $indRowId;
  7115.             $inStorage $em->getRepository('ApplicationBundle:InventoryStorage')
  7116.                 ->findBy(
  7117.                     array(
  7118.                         'productId' => $productId,
  7119.                         'warehouseId' => $warehouseId,
  7120.                         'actionTagId' => $warehouseActionId,
  7121.                         'CompanyId' => $companyId,
  7122.                     )
  7123.                 );
  7124.             foreach ($inStorage as $strg) {
  7125.                 $data['availableQty'] += $strg->getQty();
  7126.             }
  7127.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  7128.                 ->findBy(
  7129.                     array(
  7130.                         'productId' => $productId,
  7131.                         'warehouseId' => $warehouseId,
  7132.                         'warehouseActionId' => $warehouseActionId,
  7133.                         'CompanyId' => $companyId,
  7134.                     )
  7135.                 );
  7136.             foreach ($productByCodeData as $pbc) {
  7137.                 $data['productByCodesArray'][] = array(
  7138.                     'id' => $pbc->getProductByCodeId(),
  7139.                     'productId' => $pbc->getProductId(),
  7140.                     'warehouseId' => $pbc->getWarehouseId(),
  7141.                     'warehouseActionId' => $pbc->getWarehouseActionId(),
  7142. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7143.                     'sales_code' => str_pad($pbc->getSalesCode(), 13'0'STR_PAD_LEFT),
  7144. //                'sales_code'=>$d['sales_code'],
  7145.                 );
  7146.             }
  7147.             return new JsonResponse(array(
  7148.                     'success' => true,
  7149.                     'data' => $data,
  7150.                 )
  7151.             );
  7152.         }
  7153.         return new JsonResponse(
  7154.             array(
  7155.                 'success' => false,
  7156.                 'data' => $data,
  7157.             )
  7158.         );
  7159.     }
  7160.     public function ProductByCodeListAjaxAction(Request $request$queryStr '')
  7161.     {
  7162.         $em $this->getDoctrine()->getManager();
  7163.         $companyId $this->getLoggedUserCompanyId($request);
  7164.         $company_data Company::getCompanyData($em$companyId);
  7165.         $data = [];
  7166.         $html '';
  7167.         $productByCodeData = [];
  7168.         if ($request->request->has('query') && $queryStr == '')
  7169.             $queryStr $request->request->get('queryStr');
  7170.         $get_kids_sql "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
  7171.                             sales_code ,
  7172.                             serial_no,
  7173.                             imei1,
  7174.                             imei2,
  7175.                             imei3,
  7176.                             imei4
  7177.                             from product_by_code
  7178.                             where ( CONVERT(sales_code,char)  like '%" $queryStr "%'
  7179.                                     or  CONVERT(serial_no,char)  like '%" $queryStr "%'
  7180.                                     or  CONVERT(imei1,char)  like '%" $queryStr "%'
  7181.                                     or  CONVERT(imei2,char)  like '%" $queryStr "%'
  7182.                                     or  CONVERT(imei3,char)  like '%" $queryStr "%'
  7183.                                     or  CONVERT(imei4,char)  like '%" $queryStr "%'
  7184.                                     ) ";
  7185.         if ($request->query->has('warehouseId'))
  7186.             $get_kids_sql .= " and warehouse_id=" $request->query->get('warehouseId') . " ";
  7187.         if ($request->query->has('position'))
  7188.             $get_kids_sql .= " and position=" $request->query->get('position') . " ";
  7189.         if ($request->query->has('deliveryReceiptId'))
  7190.             $get_kids_sql .= " and deliveryReceiptId=" $request->query->get('deliveryReceiptId') . " ";
  7191.         if ($request->query->has('warehouseActionId'))
  7192.             $get_kids_sql .= " and warehouse_action_id=" $request->query->get('warehouseActionId') . " ";
  7193.         if ($request->query->has('productId'))
  7194.             $get_kids_sql .= " and product_id=" $request->query->get('productId') . " ";
  7195.         $get_kids_sql .= " and company_id=" $companyId " limit 25";
  7196.         $stmt $em->getConnection()->prepare($get_kids_sql);
  7197.         $stmt->execute();
  7198.         $get_kids $stmt->fetchAll();
  7199.         if (!empty($get_kids)) {
  7200.             foreach ($get_kids as $d) {
  7201.                 $dt = array(
  7202.                     'id' => $d['id'],
  7203.                     'productId' => $d['product_id'],
  7204.                     'warehouseId' => $d['warehouse_id'],
  7205.                     'warehouseActionId' => $d['warehouse_action_id'],
  7206. //                'sales_code'=>sprintf("%013d",$d['sales_code']),
  7207.                     'sales_code' => str_pad($d['sales_code'], 13'0'STR_PAD_LEFT),
  7208.                     'serial_no' => str_pad($d['serial_no'], 13'0'STR_PAD_LEFT),
  7209.                     'imei1' => str_pad($d['imei1'], 13'0'STR_PAD_LEFT),
  7210.                     'imei2' => str_pad($d['imei2'], 13'0'STR_PAD_LEFT),
  7211.                     'imei3' => str_pad($d['imei3'], 13'0'STR_PAD_LEFT),
  7212.                     'imei4' => str_pad($d['imei4'], 13'0'STR_PAD_LEFT),
  7213. //                'sales_code'=>$d['sales_code'],
  7214.                 );
  7215.                 $data[] = $dt;
  7216.             }
  7217.         }
  7218. //        if($request->query->has('returnJson'))
  7219.         {
  7220.             return new JsonResponse(
  7221.                 array(
  7222.                     'success' => true,
  7223. //                    'page_title' => 'Product Details',
  7224. //                    'company_data' => $company_data,
  7225.                     'data' => $data,
  7226. //                    'exId'=>$id,
  7227. //                'productByCodeData' => $productByCodeData,
  7228. //                'productData' => $productData,
  7229. //                'currInvList' => $currInvList,
  7230. //                'productList' => Inventory::ProductList($em, $companyId),
  7231. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  7232. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  7233. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  7234. //                'unitList' => Inventory::UnitTypeList($em),
  7235. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  7236. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  7237. //                'warehouseList' => Inventory::WarehouseList($em),
  7238.                 )
  7239.             );
  7240.         }
  7241.     }
  7242.     public function selectDataAjaxAction(Request $request$queryStr '')
  7243.     {
  7244.         $em $this->getDoctrine()->getManager();
  7245.         if ($request->request->get('entity_group'0)) {
  7246.             $companyId 0;
  7247.             $em $this->getDoctrine()->getManager('company_group');
  7248.         } else {
  7249.             if ($request->request->get('appId'0) != 0) {
  7250.                 $gocEnabled 0;
  7251.                 if ($this->container->hasParameter('entity_group_enabled'))
  7252.                     $gocEnabled $this->container->getParameter('entity_group_enabled');
  7253.                 else
  7254.                     $gocEnabled 1;
  7255.                 if ($gocEnabled == 1) {
  7256.                     $dataToConnect System::changeDoctrineManagerByAppId(
  7257.                         $this->getDoctrine()->getManager('company_group'),
  7258.                         $gocEnabled,
  7259.                         $request->request->get('appId'0)
  7260.                     );
  7261.                     if (!empty($dataToConnect)) {
  7262.                         $connector $this->container->get('application_connector');
  7263.                         $connector->resetConnection(
  7264.                             'default',
  7265.                             $dataToConnect['dbName'],
  7266.                             $dataToConnect['dbUser'],
  7267.                             $dataToConnect['dbPass'],
  7268.                             $dataToConnect['dbHost'],
  7269.                             $reset true
  7270.                         );
  7271.                         $em $this->getDoctrine()->getManager();
  7272.                     }
  7273.                 }
  7274.             }
  7275.             $companyId $this->getLoggedUserCompanyId($request);
  7276.         }
  7277.         if ($companyId) {
  7278.             $company_data = [];
  7279. //            $company_data = Company::getCompanyData($em, $companyId);
  7280.         } else {
  7281.             $companyId 0;
  7282.             $company_data = [];
  7283.         }
  7284.         $data = [];
  7285.         $data_by_id = [];
  7286.         $html '';
  7287.         $productByCodeData = [];
  7288.         $setValueArray = [];
  7289.         $setValue 0;
  7290.         $setValueType 0;// 0 for id , 1 for query
  7291.         $selectAll 0;
  7292.         if ($queryStr == '_EMPTY_')
  7293.             $queryStr '';
  7294.         if ($request->request->has('query'))
  7295.             $queryStr $request->request->get('query');
  7296.         if ($queryStr == '_EMPTY_')
  7297.             $queryStr '';
  7298.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  7299.         if ($queryStr === '#setValue:') {
  7300.             $queryStr '';
  7301.         }
  7302.         if (!(strpos($queryStr'#setValue:') === false)) {
  7303.             $setValueArrayBeforeFilter explode(','str_replace('#setValue:'''$queryStr));
  7304.             foreach ($setValueArrayBeforeFilter as $svf) {
  7305.                 if ($svf == '_ALL_') {
  7306.                     $selectAll 1;
  7307.                     $setValueArray = [];
  7308.                     continue;
  7309.                 }
  7310.                 if (is_numeric($svf)) {
  7311.                     $setValueArray[] = ($svf 1);
  7312.                     $setValue $svf 1;
  7313.                 }
  7314.             }
  7315.             $queryStr '';
  7316.         }
  7317. //        if (!(strpos($queryStr, '#setValueByQuery:') === false)) {
  7318. //            $setValueArrayBeforeFilter = explode(',', str_replace('#setValueByQuery:', '', $queryStr));
  7319. //
  7320. //            foreach ($setValueArrayBeforeFilter as $svf) {
  7321. //                if ($svf == '_ALL_') {
  7322. //                    $selectAll = 1;
  7323. //                    $setValueArray = [];
  7324. //                    continue;
  7325. //                }
  7326. //                if (is_numeric($svf)) {
  7327. //                    $setValueArray[] = ($svf * 1);
  7328. //                    $setValue = $svf * 1;
  7329. //                }
  7330. //            }
  7331. //
  7332. //            $queryStr = '';
  7333. //
  7334. //
  7335. //        }
  7336. //            $setValue = str_replace('#setValue:','',$queryStr);
  7337.         $valueField $request->request->has('valueField') ? $request->request->get('valueField') : 'id';
  7338.         $itemLimit $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25;
  7339.         $selectorId $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_';
  7340.         $textField $request->request->has('textField') ? $request->request->get('textField') : 'name';
  7341.         $table $request->request->has('tableName') ? $request->request->get('tableName') : '';
  7342.         $isMultiple $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0;
  7343.         $orConditions $request->request->has('orConditions') ? $request->request->get('orConditions') : [];
  7344.         $andConditions $request->request->has('andConditions') ? $request->request->get('andConditions') : [];
  7345.         $andOrConditions $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [];
  7346.         $mustConditions $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [];
  7347.         $joinTableData $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [];
  7348.         $renderTextFormat $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '';
  7349.         $setDataForSingle $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0;
  7350.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  7351.         $lastChildrenOnly $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0;
  7352.         $parentIdField $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id';
  7353.         $skipDefaultCompanyId $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1;
  7354.         $offset $request->request->has('offset') ? $request->request->get('offset') : 0;
  7355.         $returnTotalMatchedEntriesFlag $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0;
  7356.         $nextOffset 0;
  7357.         $totalMatchedEntries 0;
  7358.         $convertToObjectFieldList $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [];
  7359.         $convertDateToStringFieldList $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [];
  7360.         $orderByConditions $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [];
  7361.         $convertToUrl $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [];
  7362.         if (is_string($andConditions)) $andConditions json_decode($andConditionstrue);
  7363.         if (is_string($orConditions)) $orConditions json_decode($orConditionstrue);
  7364.         if (is_string($andOrConditions)) $andOrConditions json_decode($andOrConditionstrue);
  7365.         if (is_string($mustConditions)) $mustConditions json_decode($mustConditionstrue);
  7366.         if (is_string($joinTableData)) $joinTableData json_decode($joinTableDatatrue);
  7367.         if (is_string($convertToObjectFieldList)) $convertToObjectFieldList json_decode($convertToObjectFieldListtrue);
  7368.         if (is_string($orderByConditions)) $orderByConditions json_decode($orderByConditionstrue);
  7369.         if (is_string($convertToUrl)) $convertToUrl json_decode($convertToUrltrue);
  7370.         if ($table == '') {
  7371.             return new JsonResponse(
  7372.                 array(
  7373.                     'success' => false,
  7374. //                    'page_title' => 'Product Details',
  7375. //                    'company_data' => $company_data,
  7376.                     'currentTs' => (new \Datetime())->format('U'),
  7377.                     'isMultiple' => $isMultiple,
  7378.                     'setValueArray' => $setValueArray,
  7379.                     'setValue' => $setValue,
  7380.                     'data' => $data,
  7381.                     'dataId' => $dataId,
  7382.                     'selectorId' => $selectorId,
  7383.                     'dataById' => $data_by_id,
  7384.                     'selectedId' => 0,
  7385.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  7386.                 )
  7387.             );
  7388.         }
  7389.         $restrictionData = array(
  7390. //            'table'=>'relevantField in restriction'
  7391.             'warehouse_action' => 'warehouseActionIds',
  7392.             'branch' => 'branchIds',
  7393.             'warehouse' => 'warehouseIds',
  7394.             'production_process_settings' => 'productionProcessIds',
  7395.         );
  7396.         $restrictionIdList = [];
  7397.         $filterQryForCriteria "select ";
  7398.         $selectQry "";
  7399. //        $selectQry=" `$table`.* ";
  7400.         $selectFieldList $request->request->has('selectFieldList') ? $request->request->get('selectFieldList') : ['*'];
  7401.         $selectPrefix $request->request->has('selectPrefix') ? $request->request->get('selectPrefix') : '';
  7402.         if (is_string($selectFieldList)) $selectFieldList json_decode($selectFieldListtrue);
  7403.         foreach ($selectFieldList as $selField) {
  7404.             if ($selectQry != '')
  7405.                 $selectQry .= ", ";
  7406.             if ($selField == '*')
  7407.                 $selectQry .= " `$table`.$selField ";
  7408.             else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7409.                 if ($selectPrefix == '')
  7410.                     $selectQry .= " count(*)  ";
  7411.                 else
  7412.                     $selectQry .= (" count(*  )  $selectPrefix"_RESULT_COUNT_ ");
  7413.             } else {
  7414.                 if ($selectPrefix == '')
  7415.                     $selectQry .= " `$table`.`$selField` ";
  7416.                 else
  7417.                     $selectQry .= (" `$table`.`$selField`  $selectPrefix"$selField ");
  7418.             }
  7419.         }
  7420.         $joinQry " from $table ";
  7421. //        $filterQryForCriteria = "select * from $table ";
  7422.         foreach ($joinTableData as $joinIndex => $joinTableDatum) {
  7423. //            $conditionStr.=' 1=1 ';
  7424.             $joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
  7425.             $joinTableAlias $joinTableName '_' $joinIndex;
  7426.             $joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''//field of main table
  7427.             $joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''//field of joining table
  7428.             $fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
  7429.             $tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
  7430.             $selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
  7431.             $selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
  7432.             $joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
  7433.             if (is_string($joinAndConditions)) $joinAndConditions json_decode($joinAndConditionstrue);
  7434.             foreach ($selectFieldList as $selField) {
  7435.                 if ($selField == '*')
  7436.                     $selectQry .= ", `$joinTableAlias`.$selField ";
  7437.                 else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
  7438.                     if ($selectPrefix == '')
  7439.                         $selectQry .= ", count(`$joinTableAlias`." $joinTableOnField ")  ";
  7440.                     else
  7441.                         $selectQry .= (", count(`$joinTableAlias`." $joinTableOnField ")  $selectPrefix"_RESULT_COUNT_ ");
  7442.                 } else {
  7443.                     if ($selectPrefix == '')
  7444.                         $selectQry .= ", `$joinTableAlias`.`$selField`  ";
  7445.                     else
  7446.                         $selectQry .= (", `$joinTableAlias`.`$selField`  $selectPrefix"$selField ");
  7447.                 }
  7448.             }
  7449.             $joinQry .= $tableJoinType $joinTableName $joinTableAlias on  ";
  7450. //            if($joinTablePrimaryField!='')
  7451. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7452. //            $joinAndString = '';
  7453.             $joinAndString '';
  7454.             if ($joinTablePrimaryField != '')
  7455.                 $joinAndString .= "  `$joinTableAlias`.`$joinTableOnField$fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7456.             foreach ($joinAndConditions as $andCondition) {
  7457. //            $conditionStr.=' 1=1 ';
  7458.                 $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7459.                 $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7460.                 $aliasInCondition $table;
  7461.                 if (!(strpos($cfield'.') === false)) {
  7462.                     $fullCfieldArray explode('.'$cfield);
  7463.                     $aliasInCondition $fullCfieldArray[0];
  7464.                     $cfield $fullCfieldArray[1];
  7465.                 }
  7466.                 $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
  7467.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7468.                     if ($joinAndString != '')
  7469.                         $joinAndString .= " and ";
  7470.                     if ($ctype == 'like') {
  7471.                         $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $cvalue "%' ");
  7472.                         $wordsBySpaces explode(' '$cvalue);
  7473.                         foreach ($wordsBySpaces as $word) {
  7474.                             if ($joinAndString != '')
  7475.                                 $joinAndString .= " and ";
  7476.                             $joinAndString .= ("`$joinTableAlias`.$cfield like '%" $word "%' ");
  7477.                         }
  7478.                     } else if ($ctype == 'not like') {
  7479.                         $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $cvalue "%' ");
  7480.                         $wordsBySpaces explode(' '$cvalue);
  7481.                         foreach ($wordsBySpaces as $word) {
  7482.                             if ($joinAndString != '')
  7483.                                 $joinAndString .= " and ";
  7484.                             $joinAndString .= ("`$joinTableAlias`.$cfield not like '%" $word "%' ");
  7485.                         }
  7486.                     } else if ($ctype == 'not_in') {
  7487.                         $joinAndString .= " ( ";
  7488.                         if (in_array('null'$cvalue)) {
  7489.                             $joinAndString .= " `$joinTableAlias`.$cfield is not null";
  7490.                             $cvalue array_diff($cvalue, ['null']);
  7491.                             if (!empty($cvalue))
  7492.                                 $joinAndString .= " and ";
  7493.                         }
  7494.                         if (in_array(''$cvalue)) {
  7495.                             $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7496.                             $cvalue array_diff($cvalue, ['']);
  7497.                             if (!empty($cvalue))
  7498.                                 $joinAndString .= " and ";
  7499.                         }
  7500.                         $joinAndString .= "`$joinTableAlias`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7501.                     } else if ($ctype == 'in') {
  7502.                         if (in_array('null'$cvalue)) {
  7503.                             $joinAndString .= "`$joinTableAlias`.$cfield is null";
  7504.                             $cvalue array_diff($cvalue, ['null']);
  7505.                             if (!empty($cvalue))
  7506.                                 $joinAndString .= " and ";
  7507.                         }
  7508.                         if (in_array(''$cvalue)) {
  7509.                             $joinAndString .= "`$joinTableAlias`.$cfield = '' ";
  7510.                             $cvalue array_diff($cvalue, ['']);
  7511.                             if (!empty($cvalue))
  7512.                                 $joinAndString .= " and ";
  7513.                         }
  7514.                         $joinAndString .= "`$joinTableAlias`.$cfield in (" implode(','$cvalue) . ") ";
  7515.                     } else if ($ctype == '=') {
  7516. //                        if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
  7517. //                            $fullCfieldArray = explode('.', $cfield);
  7518. //                            $aliasInCondition = $fullCfieldArray[0];
  7519. //                            $cfield = $fullCfieldArray[1];
  7520. //                        }
  7521.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7522.                             $joinAndString .= "`$joinTableAlias`.$cfield is null ";
  7523.                         else
  7524.                             $joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
  7525.                     } else if ($ctype == '!=') {
  7526.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7527.                             $joinAndString .= "`$joinTableAlias`.$cfield is not null ";
  7528.                         else
  7529.                             $joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
  7530.                     } else {
  7531.                         if (is_string($cvalue))
  7532.                             $joinAndString .= "`$joinTableAlias`.$cfield $ctype '" $cvalue "' ";
  7533.                         else
  7534.                             $joinAndString .= "`$joinTableAlias`.$cfield $ctype " $cvalue " ";
  7535.                     }
  7536.                 }
  7537.             }
  7538. //            if ($joinAndString != '') {
  7539. //                if ($conditionStr != '')
  7540. //                    $conditionStr .= (" and (" . $joinAndString . ") ");
  7541. //                else
  7542. //                    $conditionStr .= ("  (" . $joinAndString . ") ");
  7543. //            }
  7544.             if ($joinAndString != '')
  7545.                 $joinQry .= $joinAndString;
  7546. //                $joinQry .= "  `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
  7547.         }
  7548.         $filterQryForCriteria .= $selectQry;
  7549.         $filterQryForCriteria .= $joinQry;
  7550.         if ($skipDefaultCompanyId == && $companyId != && !$request->request->get('entity_group'0))
  7551.             $filterQryForCriteria .= " where `$table`.`company_id`=" $companyId " ";
  7552.         else
  7553.             $filterQryForCriteria .= " where 1=1 ";
  7554.         $conditionStr "";
  7555.         if (isset($restrictionData[$table])) {
  7556.             $userRestrictionData Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'];
  7557.             if (isset($userRestrictionData[$restrictionData[$table]])) {
  7558.                 $restrictionIdList $userRestrictionData[$restrictionData[$table]];
  7559.                 if ($restrictionIdList == null)
  7560.                     $restrictionIdList = [];
  7561.             }
  7562.             if (!empty($restrictionIdList))
  7563.                 $conditionStr .= " `$table`.$valueField in (" implode(','$restrictionIdList) . ") ";
  7564.         }
  7565.         $aliasInCondition $table;
  7566.         if (!empty($setValueArray) || $selectAll == 1) {
  7567.             if (!empty($setValueArray)) {
  7568.                 if ($conditionStr != '')
  7569.                     $conditionStr .= " and ";
  7570.                 $conditionStr .= " `$aliasInCondition`.$valueField in (" implode(','$setValueArray) . ") ";
  7571.             }
  7572.         } else {
  7573.             $andString '';
  7574.             foreach ($andConditions as $andCondition) {
  7575. //            $conditionStr.=' 1=1 ';
  7576.                 $ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
  7577.                 $cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
  7578.                 $aliasInCondition $table;
  7579.                 if (!(strpos($cfield'.') === false)) {
  7580.                     $fullCfieldArray explode('.'$cfield);
  7581.                     $aliasInCondition $fullCfieldArray[0];
  7582.                     $cfield $fullCfieldArray[1];
  7583.                 }
  7584.                 $cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
  7585.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7586.                     if ($andString != '')
  7587.                         $andString .= " and ";
  7588.                     if ($ctype == 'like') {
  7589.                         $andString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7590.                         $wordsBySpaces explode(' '$cvalue);
  7591.                         foreach ($wordsBySpaces as $word) {
  7592.                             if ($andString != '')
  7593.                                 $andString .= " and ";
  7594.                             $andString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7595.                         }
  7596.                     } else if ($ctype == 'not like') {
  7597.                         $andString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7598.                         $wordsBySpaces explode(' '$cvalue);
  7599.                         foreach ($wordsBySpaces as $word) {
  7600.                             if ($andString != '')
  7601.                                 $andString .= " and ";
  7602.                             $andString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7603.                         }
  7604.                     } else if ($ctype == 'not_in') {
  7605.                         $andString .= " ( ";
  7606.                         if (in_array('null'$cvalue)) {
  7607.                             $andString .= " `$aliasInCondition`.$cfield is not null";
  7608.                             $cvalue array_diff($cvalue, ['null']);
  7609.                             if (!empty($cvalue))
  7610.                                 $andString .= " and ";
  7611.                         }
  7612.                         if (in_array(''$cvalue)) {
  7613.                             $andString .= "`$aliasInCondition`.$cfield = '' ";
  7614.                             $cvalue array_diff($cvalue, ['']);
  7615.                             if (!empty($cvalue))
  7616.                                 $andString .= " and ";
  7617.                         }
  7618.                         $andString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7619.                     } else if ($ctype == 'in') {
  7620.                         if (in_array('null'$cvalue)) {
  7621.                             $andString .= "`$aliasInCondition`.$cfield is null";
  7622.                             $cvalue array_diff($cvalue, ['null']);
  7623.                             if (!empty($cvalue))
  7624.                                 $andString .= " and ";
  7625.                         }
  7626.                         if (in_array(''$cvalue)) {
  7627.                             $andString .= "`$aliasInCondition`.$cfield = '' ";
  7628.                             $cvalue array_diff($cvalue, ['']);
  7629.                             if (!empty($cvalue))
  7630.                                 $andString .= " and ";
  7631.                         }
  7632.                         $andString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ";
  7633.                     } else if ($ctype == '=') {
  7634.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7635.                             $andString .= "`$aliasInCondition`.$cfield is null ";
  7636.                         else
  7637.                             $andString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7638.                     } else if ($ctype == '!=') {
  7639.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7640.                             $andString .= "`$aliasInCondition`.$cfield is not null ";
  7641.                         else
  7642.                             $andString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7643.                     } else {
  7644.                         if (is_string($cvalue))
  7645.                             $andString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7646.                         else
  7647.                             $andString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7648.                     }
  7649.                 }
  7650.             }
  7651.             if ($andString != '') {
  7652.                 if ($conditionStr != '')
  7653.                     $conditionStr .= (" and (" $andString ") ");
  7654.                 else
  7655.                     $conditionStr .= ("  (" $andString ") ");
  7656.             }
  7657.             $orString '';
  7658.             foreach ($orConditions as $orCondition) {
  7659.                 $ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
  7660.                 $cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
  7661.                 $aliasInCondition $table;
  7662.                 if (!(strpos($cfield'.') === false)) {
  7663.                     $fullCfieldArray explode('.'$cfield);
  7664.                     $aliasInCondition $fullCfieldArray[0];
  7665.                     $cfield $fullCfieldArray[1];
  7666.                 }
  7667.                 $cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStr;
  7668.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7669.                     if ($orString != '')
  7670.                         $orString .= " or ";
  7671.                     if ($ctype == 'like') {
  7672.                         $orString .= ("`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7673.                         $wordsBySpaces explode(' '$cvalue);
  7674.                         foreach ($wordsBySpaces as $word) {
  7675.                             if ($orString != '')
  7676.                                 $orString .= " or ";
  7677.                             $orString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7678.                         }
  7679.                     } else if ($ctype == 'not like') {
  7680.                         $orString .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7681.                         $wordsBySpaces explode(' '$cvalue);
  7682.                         foreach ($wordsBySpaces as $word) {
  7683.                             if ($orString != '')
  7684.                                 $orString .= " or ";
  7685.                             $orString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7686.                         }
  7687.                     } else if ($ctype == 'not_in') {
  7688.                         $orString .= " ( ";
  7689.                         if (in_array('null'$cvalue)) {
  7690.                             $orString .= " `$aliasInCondition`.$cfield is not null";
  7691.                             $cvalue array_diff($cvalue, ['null']);
  7692.                             if (!empty($cvalue))
  7693.                                 $orString .= " or ";
  7694.                         }
  7695.                         if (in_array(''$cvalue)) {
  7696.                             $orString .= "`$aliasInCondition`.$cfield = '' ";
  7697.                             $cvalue array_diff($cvalue, ['']);
  7698.                             if (!empty($cvalue))
  7699.                                 $orString .= " or ";
  7700.                         }
  7701.                         $orString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7702.                     } else if ($ctype == 'in') {
  7703.                         $orString .= " ( ";
  7704.                         if (in_array('null'$cvalue)) {
  7705.                             $orString .= " `$aliasInCondition`.$cfield is null";
  7706.                             $cvalue array_diff($cvalue, ['null']);
  7707.                             if (!empty($cvalue))
  7708.                                 $orString .= " or ";
  7709.                         }
  7710.                         if (in_array(''$cvalue)) {
  7711.                             $orString .= "`$aliasInCondition`.$cfield = '' ";
  7712.                             $cvalue array_diff($cvalue, ['']);
  7713.                             if (!empty($cvalue))
  7714.                                 $orString .= " or ";
  7715.                         }
  7716.                         $orString .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7717.                     } else if ($ctype == '=') {
  7718.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7719.                             $orString .= "`$aliasInCondition`.$cfield is null ";
  7720.                         else
  7721.                             $orString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7722.                     } else if ($ctype == '!=') {
  7723.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7724.                             $orString .= "`$aliasInCondition`.$cfield is not null ";
  7725.                         else
  7726.                             $orString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7727.                     } else {
  7728.                         if (is_string($cvalue))
  7729.                             $orString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7730.                         else
  7731.                             $orString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7732.                     }
  7733.                 }
  7734.             }
  7735.             if ($orString != '') {
  7736.                 if ($conditionStr != '')
  7737.                     $conditionStr .= (" or (" $orString ") ");
  7738.                 else
  7739.                     $conditionStr .= ("  (" $orString ") ");
  7740.             }
  7741.             $andOrString '';
  7742.             foreach ($andOrConditions as $andOrCondition) {
  7743.                 $ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
  7744.                 $cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
  7745.                 $aliasInCondition $table;
  7746.                 if (!(strpos($cfield'.') === false)) {
  7747.                     $fullCfieldArray explode('.'$cfield);
  7748.                     $aliasInCondition $fullCfieldArray[0];
  7749.                     $cfield $fullCfieldArray[1];
  7750.                 }
  7751.                 $cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStr;
  7752.                 if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7753.                     if ($andOrString != '')
  7754.                         $andOrString .= " or ";
  7755.                     if ($ctype == 'like') {
  7756.                         $andOrString .= (" `$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7757.                         $wordsBySpaces explode(' '$cvalue);
  7758.                         foreach ($wordsBySpaces as $word) {
  7759.                             if ($andOrString != '')
  7760.                                 $andOrString .= " or ";
  7761.                             $andOrString .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7762.                         }
  7763.                     } else if ($ctype == 'not like') {
  7764.                         $andOrString .= (" `$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7765.                         $wordsBySpaces explode(' '$cvalue);
  7766.                         foreach ($wordsBySpaces as $word) {
  7767.                             if ($andOrString != '')
  7768.                                 $andOrString .= " or ";
  7769.                             $andOrString .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7770.                         }
  7771.                     } else if ($ctype == 'in') {
  7772.                         $andOrString .= " ( ";
  7773.                         if (in_array('null'$cvalue)) {
  7774.                             $andOrString .= " `$aliasInCondition`.$cfield is null";
  7775.                             $cvalue array_diff($cvalue, ['null']);
  7776.                             if (!empty($cvalue))
  7777.                                 $andOrString .= " or ";
  7778.                         }
  7779.                         if (in_array(''$cvalue)) {
  7780.                             $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  7781.                             $cvalue array_diff($cvalue, ['']);
  7782.                             if (!empty($cvalue))
  7783.                                 $andOrString .= " or ";
  7784.                         }
  7785.                         if (!empty($cvalue))
  7786.                             $andOrString .= " `$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7787.                         else
  7788.                             $andOrString .= "  ) ";
  7789.                     } else if ($ctype == 'not_in') {
  7790.                         $andOrString .= " ( ";
  7791.                         if (in_array('null'$cvalue)) {
  7792.                             $andOrString .= " `$aliasInCondition`.$cfield is not null";
  7793.                             $cvalue array_diff($cvalue, ['null']);
  7794.                             if (!empty($cvalue))
  7795.                                 $andOrString .= " or ";
  7796.                         }
  7797.                         if (in_array(''$cvalue)) {
  7798.                             $andOrString .= "`$aliasInCondition`.$cfield = '' ";
  7799.                             $cvalue array_diff($cvalue, ['']);
  7800.                             if (!empty($cvalue))
  7801.                                 $andOrString .= " or ";
  7802.                         }
  7803.                         if (!empty($cvalue))
  7804.                             $andOrString .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7805.                         else
  7806.                             $andOrString .= "  ) ";
  7807.                     } else if ($ctype == '=') {
  7808.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7809.                             $andOrString .= "`$aliasInCondition`.$cfield is null ";
  7810.                         else
  7811.                             $andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
  7812.                     } else if ($ctype == '!=') {
  7813.                         if ($cvalue == 'null' || $cvalue == 'Null')
  7814.                             $andOrString .= "`$aliasInCondition`.$cfield is not null ";
  7815.                         else
  7816.                             $andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
  7817.                     } else {
  7818.                         if (is_string($cvalue))
  7819.                             $andOrString .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7820.                         else
  7821.                             $andOrString .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7822.                     }
  7823.                 }
  7824.             }
  7825.             if ($andOrString != '') {
  7826.                 if ($conditionStr != '')
  7827.                     $conditionStr .= (" and (" $andOrString ") ");
  7828.                 else
  7829.                     $conditionStr .= ("  (" $andOrString ") ");
  7830.             }
  7831.         }
  7832.         $mustStr '';
  7833. ///now must conditions
  7834.         foreach ($mustConditions as $mustCondition) {
  7835. //            $conditionStr.=' 1=1 ';
  7836.             $ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
  7837.             $cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
  7838.             $aliasInCondition $table;
  7839.             if (!(strpos($cfield'.') === false)) {
  7840.                 $fullCfieldArray explode('.'$cfield);
  7841.                 $aliasInCondition $fullCfieldArray[0];
  7842.                 $cfield $fullCfieldArray[1];
  7843.             }
  7844.             $cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStr;
  7845.             if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
  7846.                 if ($mustStr != '')
  7847.                     $mustStr .= " and ";
  7848.                 if ($ctype == 'like') {
  7849.                     $mustStr .= ("(`$aliasInCondition`.$cfield like '%" $cvalue "%' ");
  7850.                     $wordsBySpaces explode(' '$cvalue);
  7851.                     foreach ($wordsBySpaces as $word) {
  7852.                         if ($mustStr != '')
  7853.                             $mustStr .= " or ";
  7854.                         $mustStr .= ("`$aliasInCondition`.$cfield like '%" $word "%' ");
  7855.                     }
  7856.                     $mustStr .= " )";
  7857.                 } else if ($ctype == 'not like') {
  7858.                     $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $cvalue "%' ");
  7859.                     $wordsBySpaces explode(' '$cvalue);
  7860.                     foreach ($wordsBySpaces as $word) {
  7861.                         if ($mustStr != '')
  7862.                             $mustStr .= " and ";
  7863.                         $mustStr .= ("`$aliasInCondition`.$cfield not like '%" $word "%' ");
  7864.                     }
  7865.                 } else if ($ctype == 'in') {
  7866.                     $mustStr .= " ( ";
  7867.                     if (in_array('null'$cvalue)) {
  7868.                         $mustStr .= " `$aliasInCondition`.$cfield is null";
  7869.                         $cvalue array_diff($cvalue, ['null']);
  7870.                         if (!empty($cvalue))
  7871.                             $mustStr .= " or ";
  7872.                     }
  7873.                     if (in_array(''$cvalue)) {
  7874.                         $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  7875.                         $cvalue array_diff($cvalue, ['']);
  7876.                         if (!empty($cvalue))
  7877.                             $mustStr .= " or ";
  7878.                     }
  7879.                     $mustStr .= "`$aliasInCondition`.$cfield in (" implode(','$cvalue) . ") ) ";
  7880.                 } else if ($ctype == 'not_in') {
  7881.                     $mustStr .= " ( ";
  7882.                     if (in_array('null'$cvalue)) {
  7883.                         $mustStr .= " `$aliasInCondition`.$cfield is not null";
  7884.                         $cvalue array_diff($cvalue, ['null']);
  7885.                         if (!empty($cvalue))
  7886.                             $mustStr .= " and ";
  7887.                     }
  7888.                     if (in_array(''$cvalue)) {
  7889.                         $mustStr .= "`$aliasInCondition`.$cfield = '' ";
  7890.                         $cvalue array_diff($cvalue, ['']);
  7891.                         if (!empty($cvalue))
  7892.                             $mustStr .= " and ";
  7893.                     }
  7894.                     $mustStr .= "`$aliasInCondition`.$cfield not in (" implode(','$cvalue) . ") ) ";
  7895.                 } else if ($ctype == '=') {
  7896.                     if ($cvalue == 'null' || $cvalue == 'Null')
  7897.                         $mustStr .= "`$aliasInCondition`.$cfield is null ";
  7898.                     else
  7899.                         $mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
  7900.                 } else if ($ctype == '!=') {
  7901.                     if ($cvalue == 'null' || $cvalue == 'Null')
  7902.                         $mustStr .= "`$aliasInCondition`.$cfield is not null ";
  7903.                     else
  7904.                         $mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
  7905.                 } else {
  7906.                     if (is_string($cvalue))
  7907.                         $mustStr .= "`$aliasInCondition`.$cfield $ctype '" $cvalue "' ";
  7908.                     else
  7909.                         $mustStr .= "`$aliasInCondition`.$cfield $ctype " $cvalue " ";
  7910.                 }
  7911.             }
  7912.         }
  7913.         if ($mustStr != '') {
  7914.             if ($conditionStr != '')
  7915.                 $conditionStr .= (" and (" $mustStr ") ");
  7916.             else
  7917.                 $conditionStr .= ("  (" $mustStr ") ");
  7918.         }
  7919.         if ($conditionStr != '')
  7920.             $filterQryForCriteria .= (" and (" $conditionStr ") ");
  7921.         if ($lastChildrenOnly == 1) {
  7922.             if ($filterQryForCriteria != '')
  7923.                 $filterQryForCriteria .= ' and';
  7924.             $filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from  $table)";
  7925.         }
  7926.         if (!empty($orderByConditions)) {
  7927.             $filterQryForCriteria .= "  order by ";
  7928.             $fone 1;
  7929.             foreach ($orderByConditions as $orderByCondition) {
  7930.                 if ($fone != 1) {
  7931.                     $filterQryForCriteria .= " , ";
  7932.                 }
  7933.                 if (isset($orderByCondition['valueList'])) {
  7934.                     if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
  7935.                     if ($orderByCondition['valueList'] == null)
  7936.                         $orderByCondition['valueList'] = [];
  7937.                     $filterQryForCriteria .= "   field(" $orderByCondition['field'] . "," implode(','$orderByCondition['valueList']) . "," $orderByCondition['field'] . ") " $orderByCondition['sortType'] . " ";
  7938.                 } else
  7939.                     $filterQryForCriteria .= " " $orderByCondition['field'] . " " $orderByCondition['sortType'] . " ";
  7940.                 $fone 0;
  7941.             }
  7942.         }
  7943.         if ($returnTotalMatchedEntriesFlag == 1) {
  7944. //            $stmt = $em->getConnection()->prepare($get_kids_sql);
  7945. //            $stmt->execute();
  7946. //            $get_kids = $stmt->fetchAll();
  7947.         }
  7948.         if ($filterQryForCriteria != '')
  7949.             if (!empty($setValueArray) || $selectAll == 1) {
  7950.             } else {
  7951.                 if ($itemLimit != '_ALL_')
  7952.                     $filterQryForCriteria .= "  limit $offset$itemLimit ";
  7953.                 else
  7954.                     $filterQryForCriteria .= "  limit $offset, 18446744073709551615 ";
  7955.             }
  7956.         $get_kids_sql $filterQryForCriteria;
  7957.         $stmt $em->getConnection()->prepare($get_kids_sql);
  7958.         $stmt->execute();
  7959.         $get_kids $stmt->fetchAll();
  7960.         $selectedId 0;
  7961.         if ($table == 'warehouse_action') {
  7962.             if (empty($get_kids)) {
  7963.                 $get_kids_sql_2 "select * from warehouse_action";
  7964.                 $stmt $em->getConnection()->prepare($get_kids_sql_2);
  7965.                 $stmt->execute();
  7966.                 $get_kids2 $stmt->fetchAll();
  7967.                 if (empty($get_kids2))
  7968.                     $get_kids GeneralConstant::$warehouse_action_list;
  7969.             }
  7970.         }
  7971.         if (!empty($get_kids)) {
  7972.             $nextOffset $offset count($get_kids);
  7973.             $nextOffset++;
  7974.             foreach ($get_kids as $pa) {
  7975.                 if (!empty($setValueArray) && $selectAll == 0) {
  7976.                     if (!in_array($pa[$valueField], $setValueArray))
  7977.                         continue;
  7978.                 }
  7979.                 if (!empty($restrictionIdList)) {
  7980.                     if (!in_array($pa[$valueField], $restrictionIdList))
  7981.                         continue;
  7982.                 }
  7983.                 if ($selectAll == 1) {
  7984.                     $setValueArray[] = $pa[$valueField];
  7985.                     $setValue $pa[$valueField];
  7986.                 } else if (count($get_kids) == && $setDataForSingle == 1) {
  7987.                     $setValueArray[] = $pa[$valueField];
  7988.                     $setValue $pa[$valueField];
  7989.                 }
  7990.                 if ($valueField != '')
  7991.                     $pa['value'] = $pa[$valueField];
  7992.                 $renderedText $renderTextFormat;
  7993.                 $compare_array = [];
  7994.                 if ($renderTextFormat != '') {
  7995.                     $renderedText $renderTextFormat;
  7996.                     $compare_arrayFull = [];
  7997.                     $compare_array = [];
  7998.                     $toBeReplacedData = array(//                        'curr'=>'tobereplaced'
  7999.                     );
  8000.                     preg_match_all("/__\w+__/"$renderedText$compare_arrayFull);
  8001.                     if (isset($compare_arrayFull[0]))
  8002.                         $compare_array $compare_arrayFull[0];
  8003. //                   $compare_array= preg_split("/__\w+__/",$renderedText);
  8004.                     foreach ($compare_array as $cmpdt) {
  8005.                         $tbr str_replace("__"""$cmpdt);
  8006.                         if ($tbr != '') {
  8007.                             if (isset($pa[$tbr])) {
  8008.                                 if ($pa[$tbr] == null)
  8009.                                     $renderedText str_replace($cmpdt''$renderedText);
  8010.                                 else
  8011.                                     $renderedText str_replace($cmpdt$pa[$tbr], $renderedText);
  8012.                             } else {
  8013.                                 $renderedText str_replace($cmpdt''$renderedText);
  8014.                             }
  8015.                         }
  8016.                     }
  8017.                 }
  8018.                 $pa['rendered_text'] = $renderedText;
  8019.                 $pa['text'] = ($textField != '' $pa[$textField] : '');
  8020. //                $pa['compare_array'] = $compare_array;
  8021.                 foreach ($convertToObjectFieldList as $convField) {
  8022.                     if (isset($pa[$convField])) {
  8023.                         $taA json_decode($pa[$convField], true);
  8024.                         if ($taA == null$taA = [];
  8025.                         $pa[$convField] = $taA;
  8026.                     } else {
  8027.                         $pa[$convField] = [];
  8028.                     }
  8029.                 }
  8030.                 foreach ($convertDateToStringFieldList as $convField) {
  8031.                     if (is_array($convField)) {
  8032.                         $fld $convField['field'];
  8033.                         $frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
  8034.                     } else {
  8035.                         $fld $convField;
  8036.                         $frmt 'Y-m-d H:i:s';
  8037.                     }
  8038.                     if (isset($pa[$fld])) {
  8039.                         $taA = new \DateTime($pa[$fld]);
  8040.                         $pa[$fld] = $taA->format($frmt);
  8041.                     }
  8042.                 }
  8043.                 foreach ($convertToUrl as $convField) {
  8044.                     $fld $convField;
  8045.                     if (isset($pa[$fld])) {
  8046.                         $pa[$fld] =
  8047.                             $this->generateUrl(
  8048.                                 $pa[$fld], [
  8049. //                                'refRoute' => $refRoute
  8050.                             ], UrlGenerator::ABSOLUTE_URL
  8051.                             );
  8052.                     }
  8053.                 }
  8054.                 $pa['currentTs'] = (new \Datetime())->format('U');
  8055.                 $data[] = $pa;
  8056.                 if ($valueField != '') {
  8057.                     $data_by_id[$pa[$valueField]] = $pa;
  8058.                     $selectedId $pa[$valueField];
  8059.                 }
  8060.             }
  8061.         }
  8062. //        if($request->query->has('returnJson'))
  8063.         {
  8064.             return new JsonResponse(
  8065.                 array(
  8066.                     'success' => true,
  8067.                     'data' => $data,
  8068.                     'tableName' => $table,
  8069.                     'setValue' => $setValue,
  8070.                     'currentTs' => (new \Datetime())->format('U'),
  8071.                     'restrictionIdList' => $restrictionIdList,
  8072.                     'andConditions' => $andConditions,
  8073.                     'queryStr' => $queryStr,
  8074.                     'isMultiple' => $isMultiple,
  8075.                     'nextOffset' => $nextOffset,
  8076.                     'totalMatchedEntries' => $totalMatchedEntries,
  8077.                     'selectorId' => $selectorId,
  8078.                     'setValueArray' => $setValueArray,
  8079.                     'conditionStr' => $conditionStr,
  8080. //                    'andStr' => $andString,
  8081. //                    'andOrStr' => $andOrString,
  8082.                     'dataById' => $data_by_id,
  8083.                     'selectedId' => $selectedId,
  8084.                     'dataId' => $dataId,
  8085.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8086.                 )
  8087.             );
  8088.         }
  8089.     }
  8090.     public function updatePlanningItemSequenceAction(Request $request$queryStr '')
  8091.     {
  8092.         $em $this->getDoctrine()->getManager();
  8093.         $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null 
  8094.             ORDER BY parent_id ASC, id ASC
  8095.                         ");
  8096.         $stmt->execute();
  8097.         $query_output $stmt->fetchAll();
  8098.         foreach ($query_output as $dupe) {
  8099.             System::updatePlanningItemSequence($em$dupe["id"]);
  8100.         }
  8101.         System::updatePlanningItemSequence(
  8102.             $em,
  8103.             $request->request->get('planningItemId'0),
  8104.             $request->request->get('assignType''_ASSIGN_')   ///can be _MOVE_UP_ or _MOVE_DOWN_
  8105.         );
  8106. //        if($request->query->has('returnJson'))
  8107.         return new JsonResponse(
  8108.             array(
  8109.                 'success' => true,
  8110.                 'data' => [],
  8111.             )
  8112.         );
  8113.     }
  8114.     public function insertDataAjaxAction(Request $request$queryStr '')
  8115.     {
  8116.         $em $this->getDoctrine()->getManager();
  8117. //        if($request->query->has('big_data_test'))
  8118. //        {
  8119. //            for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
  8120. //                $em = $this->getDoctrine()->getManager('company_group');
  8121. //                $NOTIFICATION = new EntityNotification();
  8122. //                $NOTIFICATION->setAppId(1);
  8123. //                $NOTIFICATION->setCompanyId(0);
  8124. //                $NOTIFICATION->setCompanyId(0);
  8125. //                $NOTIFICATION->setBody('Test Description'.$t);
  8126. //                $NOTIFICATION->setTitle('Test Title'.$t);
  8127. //                $NOTIFICATION->setExpireTs(0);
  8128. //                $NOTIFICATION->setIsBuddybee(0);
  8129. //                $NOTIFICATION->setType(0);
  8130. //                $em->persist($NOTIFICATION);
  8131. //                $em->flush();
  8132. //            }
  8133. //
  8134. //            return new JsonResponse(
  8135. //                array(
  8136. //                    'success' => true,
  8137. //                    'data' => [],
  8138. //
  8139. //
  8140. //                )
  8141. //            );
  8142. //
  8143. //
  8144. //        }
  8145.         if ($request->request->get('entity_group'0)) {
  8146.             $companyId 0;
  8147.             $em $this->getDoctrine()->getManager('company_group');
  8148.         } else
  8149.             $companyId $this->getLoggedUserCompanyId($request);
  8150.         if ($companyId) {
  8151.             $company_data = [];
  8152. //            $company_data = Company::getCompanyData($em, $companyId);
  8153.         } else {
  8154.             $companyId 0;
  8155.             $company_data = [];
  8156.         }
  8157. //        $theEntity= new EntityNotification();
  8158. //        $entityName = 'EntityNotification';
  8159. //
  8160. //        $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
  8161. //
  8162. //
  8163. //            $theEntity= new $className();
  8164.         $dataToAdd $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
  8165.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8166.         if ($dataToAdd == null$dataToAdd = [];
  8167.         $dataToRemove $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
  8168.         if (is_string($dataToRemove)) $dataToAdd json_decode($dataToRemovetrue);
  8169.         if ($dataToRemove == null$dataToRemove = [];
  8170.         $relData = [];
  8171.         if (is_string($dataToAdd)) $dataToAdd json_decode($dataToAddtrue);
  8172.         $updatedDataList = [];
  8173.         foreach ($dataToAdd as $dataInd => $dat) {
  8174.             $entityName $dat['entityName'];
  8175.             $idField $dat['idField'];
  8176.             $findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
  8177.             $findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
  8178.             $returnRefIndex $dat['returnRefIndex'];
  8179.             $findById $dat['findId'];
  8180.             $dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
  8181.             $noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
  8182.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8183.             $preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
  8184.             if ($preAdditionalSql != '') {
  8185. //            if ($entityName == 'PlanningItem') {
  8186. //
  8187. //                $stmt='select disctinct parent_id from planning_item;';
  8188. //                $stmt->execute();
  8189. //                $get_kids = $stmt->fetchAll();
  8190. //                $p_ids=[];
  8191. //                foreach($get_kids as $g)
  8192. //                {
  8193. //                    $p_ids[]=$g['parent_id'];
  8194. //                }
  8195. //
  8196. //
  8197. //
  8198.                 $stmt $em->getConnection()->prepare($preAdditionalSql);
  8199.                 $stmt->execute();
  8200.                 $stmt->closeCursor();
  8201. //
  8202. //
  8203.             }
  8204.             if ($entityName == 'PlanningItem') {
  8205.                 $stmt $em->getConnection()->prepare("select  `id` , parent_id, sequence from planning_item where sequence is null
  8206.             ORDER BY parent_id ASC, id ASC
  8207.                         ");
  8208.                 $stmt->execute();
  8209.                 $query_output $stmt->fetchAll();
  8210.                 foreach ($query_output as $dupe) {
  8211.                     System::updatePlanningItemSequence($em$dupe["id"]);
  8212.                 }
  8213.             }
  8214.             $className = ($request->request->get('entity_group'0) ? '\\CompanyGroupBundle\\Entity\\' '\\ApplicationBundle\\Entity\\') . $entityName;
  8215.             if (
  8216.                 ($findById == || $findById == '_NA_') && $findByField == '' && $noCreation == 0
  8217.             ) {
  8218.                 $theEntity = new $className();
  8219. //                $theEntity= new EntityNotification();
  8220.             } else {
  8221.                 if ($findByField != '') {
  8222.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8223.                         array
  8224.                         (
  8225.                             $findByField => $findByValue,
  8226.                         )
  8227.                     );
  8228.                 } else {
  8229.                     $theEntity $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findOneBy(
  8230.                         array
  8231.                         (
  8232.                             $idField => $findById,
  8233.                         )
  8234.                     );
  8235.                 }
  8236.             }
  8237.             if (!$theEntity && $noCreation == 0)
  8238.                 $theEntity = new $className();
  8239.             foreach ($dataFields as $dt) {
  8240.                 $setMethod 'set' ucfirst($dt['field']);
  8241.                 $getMethod 'get' ucfirst($dt['field']);
  8242.                 $type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
  8243.                 $action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
  8244.                 if (method_exists($theEntity$setMethod)) {
  8245.                     $oldValue $theEntity->{$getMethod}();
  8246.                     $newValue $oldValue;
  8247.                     if ($type == '_VALUE_') {
  8248.                         $newValue $dt['value'];
  8249.                     }
  8250.                     if ($type == '_DECIMAL_') {
  8251.                         $newValue $dt['value'];
  8252.                     }
  8253.                     if ($type == '_DATE_') {
  8254.                         $newValue = new \DateTime($dt['value']);
  8255.                     }
  8256.                     if ($type == '_ARRAY_') {
  8257.                         $oldValue json_decode($oldValue);
  8258.                         if ($oldValue == null$oldValue = [];
  8259.                         if ($action == '_REPLACE_') {
  8260.                             $newValue json_encode($dt['value']);
  8261.                         }
  8262.                         if ($action == '_APPEND_') {
  8263.                             $newValue array_merge($oldValuearray_values(array_diff([$dt['value']], $oldValue)));
  8264.                         }
  8265.                         if ($action == '_MERGE_') {
  8266.                             $newValue array_merge($oldValuearray_values(array_diff($dt['value'], $oldValue)));
  8267.                         }
  8268.                         if ($action == '_EXCLUDE_') {
  8269.                             $newValue array_values(array_diff($oldValue, [$dt['value']]));
  8270.                         }
  8271.                         if ($action == '_EXCLUDE_ARRAY_') {
  8272.                             $newValue array_values(array_diff($oldValue$dt['value']));
  8273.                         }
  8274.                         $newValue json_encode($newValue);
  8275.                     }
  8276.                     $theEntity->{$setMethod}($newValue); // `foo!`
  8277. //                    $theEntity->setCompletionPercentage(78); // `foo!`
  8278.                 }
  8279.             }
  8280.             if ($additionalSql != '') {
  8281. //            if ($entityName == 'PlanningItem') {
  8282. //
  8283. //                $stmt='select disctinct parent_id from planning_item;';
  8284. //                $stmt->execute();
  8285. //                $get_kids = $stmt->fetchAll();
  8286. //                $p_ids=[];
  8287. //                foreach($get_kids as $g)
  8288. //                {
  8289. //                    $p_ids[]=$g['parent_id'];
  8290. //                }
  8291. //
  8292. //
  8293. //
  8294.                 $stmt $em->getConnection()->prepare($additionalSql);
  8295.                 $stmt->execute();
  8296.                 $stmt->closeCursor();
  8297. //
  8298. //
  8299.             }
  8300.             if (($findById == || $findById == '_NA_') && $noCreation == 0) {
  8301.                 $em->persist($theEntity);
  8302.                 $em->flush();
  8303.                 $getMethod 'get' ucfirst($idField);
  8304.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8305.             } else if ($theEntity) {
  8306.                 $em->flush();
  8307.                 $getMethod 'get' ucfirst($idField);
  8308.                 $relData[$returnRefIndex] = $theEntity->{$getMethod}();
  8309.             }
  8310.             if ($entityName == 'PlanningItem') {
  8311.                 $stmt $em->getConnection()->prepare('select distinct parent_id from planning_item;');
  8312.                 $stmt->execute();
  8313.                 $get_kids $stmt->fetchAll();
  8314.                 $p_ids = [];
  8315.                 foreach ($get_kids as $g) {
  8316.                     $p_ids[] = $g['parent_id'];
  8317.                 }
  8318.                 $stmt $em->getConnection()->prepare('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' implode(','$p_ids) . '); 
  8319.                           UPDATE planning_item d SET d.`has_child` =1 WHERE d.id  IN (' implode(','$p_ids) . ')');
  8320.                 $stmt->execute();
  8321.                 $stmt->closeCursor();
  8322.                 $updatedData System::updatePlanningItemSequence($em$theEntity->getId());
  8323.                 $theEntity $updatedData['primaryOne'];
  8324.                 $theEntityUpdated $theEntity;
  8325.                 if ($theEntityUpdated->getEntryType() == 4)///cashflow
  8326.                 {
  8327.                     MiscActions::AddCashFlowProjection($em0, [
  8328.                         'planningItemId' => $theEntityUpdated->getId(),
  8329.                         'fundRequisitionId' => 0,
  8330.                         'concernedPersonId' => 0,
  8331.                         'type' => 1//exp
  8332.                         'subType' => 1//1== khoroch hobe 2: ashbe
  8333.                         'cashFlowType' => 1//2== RCV /in  1: Payment/out
  8334.                         'creationType' => 1//auto
  8335.                         'amountType' => 1//fund
  8336.                         'cashFlowAmount' => 0,
  8337.                         'expAstAmount' => 0,
  8338.                         'accumulatedCashFlowAmount' => 0,
  8339.                         'accumulatedCashFlowBalance' => 0,
  8340.                         'accumulatedExpAstAmount' => 0,
  8341.                         'relevantExpAstHeadId' => 0,
  8342.                         'balancingHeadId' => 0,
  8343.                         'cashFlowHeadId' => 0,
  8344.                         'cashFlowHeadType' => 1,
  8345.                         'relevantProductIds' => [],
  8346.                         'reminderDateTs' => 0,
  8347.                         'cashFlowDateTs' => 0,
  8348.                         'expAstRealizationDateTs' => 0,
  8349.                     ]);
  8350.                 }
  8351.             }
  8352.             else if ($entityName == 'TaskLog') {
  8353.                 $session $request->getSession();
  8354.                 if ($theEntity) {
  8355.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8356.                     $currTime = new \DateTime();
  8357.                     $options = array(
  8358.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8359.                         'notification_server' => $this->container->getParameter('notification_server'),
  8360.                     );
  8361.                     $positionsArray = [
  8362.                         array(
  8363.                             'employeeId' => $empId,
  8364.                             'userId' => $session->get(UserConstants::USER_ID0),
  8365.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8366.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8367.                             'lat' => 23.8623834,
  8368.                             'lng' => 90.3979294,
  8369.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
  8370. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8371.                         )
  8372.                     ];
  8373.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8374.                     if ($positionsArray == null$positionsArray = [];
  8375.                     $dataByAttId = [];
  8376.                     $workPlaceType '_UNSET_';
  8377.                     foreach ($positionsArray as $findex => $d) {
  8378.                         $sysUserId 0;
  8379.                         $userId 0;
  8380.                         $empId 0;
  8381.                         $dtTs 0;
  8382.                         $timeZoneStr '+0000';
  8383.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8384.                         if (isset($d['userId'])) $userId $d['userId'];
  8385.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8386.                         if (isset($d['tsMilSec'])) {
  8387.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8388.                         }
  8389.                         if ($dtTs == 0) {
  8390.                             $currTsTime = new \DateTime();
  8391.                             $dtTs $currTsTime->format('U');
  8392.                         } else {
  8393.                             $currTsTime = new \DateTime('@' $dtTs);
  8394.                         }
  8395.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8396.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8397.                         $EmployeeAttendance $this->getDoctrine()
  8398.                             ->getRepository(EmployeeAttendance::class)
  8399.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8400.                         if (!$EmployeeAttendance) {
  8401.                             $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8402.                             $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8403.                             $EmployeeAttendance = new EmployeeAttendance;
  8404.                         } else {
  8405.                             if ($EmployeeAttendance->getCurrentLocation() == 'out') {
  8406.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8407.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
  8408.                             } else {
  8409.                                 $d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8410.                                 $positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
  8411.                             }
  8412.                         }
  8413.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8414.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
  8415.                             $workPlaceType '_STATIC_';
  8416.                         }
  8417.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8418.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8419.                                 'attendanceInfo' => $attendanceInfo,
  8420.                                 'empId' => $empId,
  8421.                                 'lat' => 0,
  8422.                                 'lng' => 0,
  8423.                                 'address' => 0,
  8424.                                 'sysUserId' => $sysUserId,
  8425.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8426.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8427.                                 'positionArray' => []
  8428.                             );
  8429.                         $posData = array(
  8430.                             'ts' => $dtTs,
  8431.                             'lat' => $d['lat'],
  8432.                             'lng' => $d['lng'],
  8433.                             'marker' => $d['markerId'],
  8434.                             'src' => 2,
  8435.                         );
  8436.                         $posDataArray = array(
  8437.                             $dtTs,
  8438.                             $d['lat'],
  8439.                             $d['lng'],
  8440.                             $d['markerId'],
  8441.                             2
  8442.                         );
  8443.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8444.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8445.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8446.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8447.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8448.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8449.                         if (isset($d['address']))
  8450.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8451. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8452.                     }
  8453.                     $response = array(
  8454.                         'success' => true,
  8455.                     );
  8456.                     foreach ($dataByAttId as $attInfoId => $d) {
  8457.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8458.                             $d['empId'],
  8459.                             $d['sysUserId'],
  8460.                             $d['companyId'],
  8461.                             $d['appId'],
  8462.                             $request,
  8463.                             $d['attendanceInfo'],
  8464.                             $options,
  8465.                             $d['positionArray'],
  8466.                             $d['lat'],
  8467.                             $d['lng'],
  8468.                             $d['address'],
  8469.                             $d['markerId']
  8470.                         );
  8471.                     }
  8472.                     $session->set(UserConstants::USER_CURRENT_TASK_ID$theEntity->getId());
  8473.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID$theEntity->getPlanningItemId());
  8474.                 }
  8475.                 else {
  8476.                     $session->set(UserConstants::USER_CURRENT_TASK_ID0);
  8477.                     $session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID0);
  8478.                     $empId $session->get(UserConstants::USER_EMPLOYEE_ID0);
  8479.                     $currTime = new \DateTime();
  8480.                     $options = array(
  8481.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8482.                         'notification_server' => $this->container->getParameter('notification_server'),
  8483.                     );
  8484.                     $positionsArray = [
  8485.                         array(
  8486.                             'employeeId' => $empId,
  8487.                             'userId' => $session->get(UserConstants::USER_ID0),
  8488.                             'sysUserId' => $session->get(UserConstants::USER_ID0),
  8489.                             'timeStamp' => $currTime->format(DATE_ISO8601),
  8490.                             'lat' => 23.8623834,
  8491.                             'lng' => 90.3979294,
  8492.                             'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
  8493. //                            'userId'=>$session->get(UserConstants::USER_ID, 0),
  8494.                         )
  8495.                     ];
  8496.                     if (is_string($positionsArray)) $positionsArray json_decode($positionsArraytrue);
  8497.                     if ($positionsArray == null$positionsArray = [];
  8498.                     $dataByAttId = [];
  8499.                     $workPlaceType '_UNSET_';
  8500.                     foreach ($positionsArray as $findex => $d) {
  8501.                         $sysUserId 0;
  8502.                         $userId 0;
  8503.                         $empId 0;
  8504.                         $dtTs 0;
  8505.                         $timeZoneStr '+0000';
  8506.                         if (isset($d['employeeId'])) $empId $d['employeeId'];
  8507.                         if (isset($d['userId'])) $userId $d['userId'];
  8508.                         if (isset($d['sysUserId'])) $sysUserId $d['sysUserId'];
  8509.                         if (isset($d['tsMilSec'])) {
  8510.                             $dtTs ceil(($d['tsMilSec']) / 1000);
  8511.                         }
  8512.                         if ($dtTs == 0) {
  8513.                             $currTsTime = new \DateTime();
  8514.                             $dtTs $currTsTime->format('U');
  8515.                         } else {
  8516.                             $currTsTime = new \DateTime('@' $dtTs);
  8517.                         }
  8518.                         $currTsTime->setTimezone(new \DateTimeZone('UTC'));
  8519.                         $attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' $timeZoneStr);
  8520.                         $EmployeeAttendance $this->getDoctrine()
  8521.                             ->getRepository(EmployeeAttendance::class)
  8522.                             ->findOneBy(array('employeeId' => $empId'date' => $attDate));
  8523.                         if (!$EmployeeAttendance) {
  8524.                             continue;
  8525.                         } else {
  8526.                         }
  8527.                         $attendanceInfo HumanResource::StoreAttendance($em$empId$sysUserId$request$EmployeeAttendance$attDate$dtTs$timeZoneStr$d['markerId']);
  8528.                         if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
  8529.                             $workPlaceType '_STATIC_';
  8530.                         }
  8531.                         if (!isset($dataByAttId[$attendanceInfo->getId()]))
  8532.                             $dataByAttId[$attendanceInfo->getId()] = array(
  8533.                                 'attendanceInfo' => $attendanceInfo,
  8534.                                 'empId' => $empId,
  8535.                                 'lat' => 0,
  8536.                                 'lng' => 0,
  8537.                                 'address' => 0,
  8538.                                 'sysUserId' => $sysUserId,
  8539.                                 'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8540.                                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8541.                                 'positionArray' => []
  8542.                             );
  8543.                         $posData = array(
  8544.                             'ts' => $dtTs,
  8545.                             'lat' => $d['lat'],
  8546.                             'lng' => $d['lng'],
  8547.                             'marker' => $d['markerId'],
  8548.                             'src' => 2,
  8549.                         );
  8550.                         $posDataArray = array(
  8551.                             $dtTs,
  8552.                             $d['lat'],
  8553.                             $d['lng'],
  8554.                             $d['markerId'],
  8555.                             2
  8556.                         );
  8557.                         $dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
  8558.                         //this markerId will be calclulted and modified to check if user is in our out of office/workplace later
  8559.                         $dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
  8560.                         $dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
  8561.                         $dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat'];  //for last lat lng etc
  8562.                         $dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng'];  //for last lat lng etc
  8563.                         if (isset($d['address']))
  8564.                             $dataByAttId[$attendanceInfo->getId()]['address'] = $d['address'];  //for last lat lng etc
  8565. //                $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
  8566.                     }
  8567.                     $response = array(
  8568.                         'success' => true,
  8569.                     );
  8570.                     foreach ($dataByAttId as $attInfoId => $d) {
  8571.                         $response HumanResource::setAttendanceLogFlutterApp($em,
  8572.                             $d['empId'],
  8573.                             $d['sysUserId'],
  8574.                             $d['companyId'],
  8575.                             $d['appId'],
  8576.                             $request,
  8577.                             $d['attendanceInfo'],
  8578.                             $options,
  8579.                             $d['positionArray'],
  8580.                             $d['lat'],
  8581.                             $d['lng'],
  8582.                             $d['address'],
  8583.                             $d['markerId']
  8584.                         );
  8585.                     }
  8586.                 }
  8587.                 $theEntityUpdated $theEntity;
  8588.             } else
  8589.                 $theEntityUpdated $theEntity;
  8590. //                $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
  8591.             $getters = [];
  8592.             if ($theEntityUpdated)
  8593.                 $getters array_filter(get_class_methods($theEntityUpdated), function ($method) {
  8594.                     return 'get' === substr($method03);
  8595.                 });
  8596.             $updatedData = [];
  8597.             foreach ($getters as $getter) {
  8598.                 $indForThis str_replace('get'''$getter);
  8599.                 $indForThis lcfirst($indForThis);
  8600.                 $updatedData[$indForThis] = $theEntityUpdated->{$getter}();
  8601.             }
  8602.             $updatedDataList[$dataInd] = $updatedData;
  8603.         }
  8604.         foreach ($dataToRemove as $dataInd => $dat) {
  8605.             $entityName $dat['entityName'];
  8606.             $idField $dat['idField'];
  8607.             $findById $dat['findId'];
  8608.             $additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
  8609.             $theEntityList $em->getRepository(($request->request->get('entity_group'0) ? 'CompanyGroupBundle:' 'ApplicationBundle:') . $entityName)->findBy(
  8610.                 array
  8611.                 (
  8612.                     $idField => $findById,
  8613.                 )
  8614.             );
  8615.             foreach ($theEntityList as $dt) {
  8616.                 $em->remove($dt);
  8617.                 $em->flush();
  8618.             }
  8619.             if ($additionalSql != '') {
  8620. //            if ($entityName == 'PlanningItem') {
  8621. //
  8622. //                $stmt='select disctinct parent_id from planning_item;';
  8623. //                $stmt->execute();
  8624. //                $get_kids = $stmt->fetchAll();
  8625. //                $p_ids=[];
  8626. //                foreach($get_kids as $g)
  8627. //                {
  8628. //                    $p_ids[]=$g['parent_id'];
  8629. //                }
  8630. //
  8631. //
  8632. //
  8633.                 $stmt $em->getConnection()->prepare($additionalSql);
  8634.                 $stmt->execute();
  8635.                 $stmt->closeCursor();
  8636. //
  8637. //
  8638.             }
  8639.             $updatedDataList[$dataInd] = [];
  8640.         }
  8641. //        if ($table == '') {
  8642. //            return new JsonResponse(
  8643. //                array(
  8644. //                    'success' => false,
  8645. ////                    'page_title' => 'Product Details',
  8646. ////                    'company_data' => $company_data,
  8647. //                    'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8648. //
  8649. //                )
  8650. //            );
  8651. //        }
  8652. //        if($request->query->has('returnJson'))
  8653.         return new JsonResponse(
  8654.             array(
  8655.                 'success' => true,
  8656.                 'data' => $relData,
  8657.                 'updatedDataList' => $updatedDataList,
  8658.             )
  8659.         );
  8660.     }
  8661.     public function GetAvailableQtyAction(Request $request$id 0)
  8662.     {
  8663.         $em $this->getDoctrine()->getManager();
  8664.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  8665.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  8666.         $dataId $request->request->has('dataId') ? $request->request->get('dataId') : 0;
  8667.         $allowedWarehouseIds $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
  8668.         $allowedWarehouseActionIds $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
  8669.         $qty Inventory::getProductQty($em$productId$allowedWarehouseIds$allowedWarehouseActionIds$colorId);
  8670.         return new JsonResponse(array("success" => true,
  8671.             "qty" => $qty,
  8672.             "dataId" => $dataId,
  8673.         ));
  8674.     }
  8675.     public
  8676.     function ProductListSelectAjaxAction(Request $request$queryStr '')
  8677.     {
  8678.         $em $this->getDoctrine()->getManager();
  8679.         $companyId $this->getLoggedUserCompanyId($request);
  8680.         $company_data Company::getCompanyData($em$companyId);
  8681.         $data = [];
  8682.         $data_by_id = [];
  8683.         $html '';
  8684.         $productByCodeData = [];
  8685.         if ($queryStr == '_EMPTY_')
  8686.             $queryStr '';
  8687.         if ($request->request->has('query') && $queryStr == '')
  8688.             $queryStr $request->request->get('queryStr');
  8689.         if ($queryStr == '_EMPTY_')
  8690.             $queryStr '';
  8691. //        $queryStr=urldecode($queryStr);
  8692.         $queryStr str_replace('_FSLASH_''/'$queryStr);
  8693.         $filterQryForCriteria "select * from inv_products where company_id=" $companyId " ";
  8694.         if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
  8695.             $filterQryForCriteria .= " and sellable=1";
  8696.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  8697.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  8698.         else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
  8699.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  8700.         else if ($request->request->has('igId') && $request->request->get('igId') != '')
  8701.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  8702.         if ($request->request->has('brandId') && $request->request->get('brandId') != '')
  8703.             $filterQryForCriteria .= " and brand_company=" $request->request->get('brandId');
  8704.         if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != [])
  8705.             $filterQryForCriteria .= " and brand_company in (" implode(','$request->request->get('restrictedBrandIds')) . ")";
  8706.         if ($request->request->has('productIds'))
  8707.             $filterQryForCriteria .= " and id in (" implode(','$request->request->get('productIds')) . ") ";
  8708.         else if ($request->request->has('productCode'))
  8709.             $filterQryForCriteria .= " and product_code  like '%" $request->request->get('productCode') . "%'  ";
  8710.         else if ($queryStr != '')
  8711.             $filterQryForCriteria .= " and  (product_code  like '%" $queryStr "%' or `name`   like '%" $queryStr "%' or model_no like '%" $queryStr "%') ";
  8712.         if ($filterQryForCriteria != '')
  8713.             $filterQryForCriteria .= "  limit 25";
  8714.         $get_kids_sql $filterQryForCriteria;
  8715. //        if ($request->request->has('productIds'))
  8716. //
  8717. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  8718. //        else if ($request->request->has('productCode'))
  8719. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  8720. //        else if ($filterQryForCriteria!='')
  8721. //            $get_kids_sql = $filterQryForCriteria;
  8722. //
  8723. //        else
  8724. //               $get_kids_sql = "select * from inv_products where (product_code  like '%" . $queryStr . "%' or `name`   like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
  8725.         $stmt $em->getConnection()->prepare($get_kids_sql);
  8726.         $stmt->execute();
  8727.         $get_kids $stmt->fetchAll();
  8728.         $productId 0;
  8729.         if (!empty($get_kids)) {
  8730.             foreach ($get_kids as $product) {
  8731.                 $pa = array();
  8732.                 $pa['id'] = $product['id'];
  8733.                 $pa['name'] = $product['name'];
  8734.                 $pa['id_name'] = $product['id'] . '. ' $product['name'];
  8735.                 $pa['id_mn'] = $product['id'] . '. ' $product['model_no'];;
  8736.                 $pa['id_name_mn'] = $product['id'] . '. ' $product['name'] . ' ( ' $product['model_no'] . ' )';
  8737.                 $pa['globalId'] = $product['global_id'];
  8738.                 $pa['classSuffix'] = $product['class_suffix'];
  8739.                 $pa['productFdm'] = $product['product_fdm'];
  8740.                 $pa['modelNo'] = $product['model_no'];
  8741.                 $pa['partId'] = $product['part_id'];
  8742.                 $pa['hsCode'] = $product['hs_code'];
  8743.                 $pa['productCode'] = $product['product_code'];
  8744.                 $pa['text'] = $product['name'];
  8745.                 $pa['value'] = $product['id'];
  8746.                 $pa['tac'] = $product['tac'];
  8747.                 $pa['igId'] = $product['ig_id'];
  8748.                 $pa['categoryId'] = $product['category_id'];
  8749.                 $pa['subCategoryId'] = $product['sub_category_id'];
  8750.                 $pa['brandCompany'] = $product['brand_company'];
  8751.                 $pa['sales_price'] = $product['curr_sales_price'];
  8752.                 $pa['purchase_price'] = $product['curr_purchase_price'];
  8753.                 $pa['unit_type'] = $product['unit_type_id'];
  8754.                 $pa['single_weight'] = $product['single_weight'];
  8755.                 $pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
  8756.                 $pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
  8757.                 $pa['weight'] = $product['weight'];
  8758.                 $pa['weight_variance_type'] = $product['weight_variance_type'];
  8759.                 $pa['weight_variance_value'] = $product['weight_variance_value'];
  8760.                 $pa['carton_capacity_count'] = $product['carton_capacity_count'];
  8761.                 $pa['type'] = $product['type'];
  8762.                 $pa['qty'] = $product['qty'];
  8763. //                $pa['alias'] = '';
  8764.                 $pa['alias'] = $product['alias'];
  8765.                 $pa['note'] = $product['note'];
  8766.                 $pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null $product['default_tax_config_id'];
  8767.                 $tax_config_ids json_decode($product['tax_config_ids'], true);
  8768.                 if ($tax_config_ids == null)
  8769.                     $tax_config_ids = [];
  8770.                 $pa['taxConfigIds'] = $tax_config_ids;
  8771.                 $inco_terms json_decode($product['inco_terms'], true);
  8772.                 if ($inco_terms == null)
  8773.                     $inco_terms = [];
  8774.                 $pa['incoTerms'] = $inco_terms;
  8775.                 $pa['defaultIncoTerm'] = $product['default_inco_term'] == null $product['default_inco_term'];
  8776.                 $pa['has_serial'] = $product['has_serial'];
  8777.                 $pa['expiry_days'] = $product['expiry_days'];
  8778.                 $pa['image'] = $product['default_image'];
  8779.                 $pa['sales_warranty'] = $product['sales_warranty_months'];;
  8780.                 $pa['defaultColorId'] = $product['default_color_id'];;
  8781.                 $allowedColorIds json_decode($product['colors'], true);
  8782.                 if ($allowedColorIds == null$allowedColorIds = [];
  8783.                 if (!in_array($product['default_color_id'], $allowedColorIds))
  8784.                     $allowedColorIds[] = $product['default_color_id'];
  8785.                 $pa['allowedColorIds'] = $allowedColorIds;;
  8786.                 $data[] = $pa;
  8787.                 $data_by_id[$product['id']] = $pa;
  8788.                 $productId $product['id'];
  8789.             }
  8790.         }
  8791. //        if($request->query->has('returnJson'))
  8792.         {
  8793.             return new JsonResponse(
  8794.                 array(
  8795.                     'success' => true,
  8796. //                    'page_title' => 'Product Details',
  8797. //                    'company_data' => $company_data,
  8798.                     'data' => $data,
  8799.                     'dataById' => $data_by_id,
  8800.                     'productId' => $productId,
  8801.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8802. //                    'exId'=>$id,
  8803. //                'productByCodeData' => $productByCodeData,
  8804. //                'productData' => $productData,
  8805. //                'currInvList' => $currInvList,
  8806. //                'productList' => Inventory::ProductList($em, $companyId),
  8807. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  8808. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  8809. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  8810. //                'unitList' => Inventory::UnitTypeList($em),
  8811. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  8812. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  8813. //                'warehouseList' => Inventory::WarehouseList($em),
  8814.                 )
  8815.             );
  8816.         }
  8817.     }
  8818.     public
  8819.     function labelFormatSelectAjaxAction(Request $request$queryStr '')
  8820.     {
  8821.         $em $this->getDoctrine()->getManager();
  8822.         $companyId $this->getLoggedUserCompanyId($request);
  8823.         $company_data Company::getCompanyData($em$companyId);
  8824.         $data = [];
  8825.         $data_by_id = [];
  8826.         $html '';
  8827.         $productByCodeData = [];
  8828.         if ($queryStr == '_EMPTY_')
  8829.             $queryStr '';
  8830.         if ($request->request->has('query') && $queryStr == '')
  8831.             $queryStr $request->request->get('queryStr');
  8832.         if ($queryStr == '_EMPTY_')
  8833.             $queryStr '';
  8834.         $filterQryForCriteria "select * from label_format where company_id=" $companyId " ";
  8835.         if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
  8836.             $filterQryForCriteria .= " and label_type=" $request->request->get('dataType');
  8837.         if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
  8838.             $filterQryForCriteria .= " and format_id=" $request->request->get('formatId');
  8839.         else if ($queryStr != '')
  8840.             $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' or `format_code` like '%" $queryStr "%') ";
  8841.         if ($filterQryForCriteria != '')
  8842.             $filterQryForCriteria .= "  limit 25";
  8843.         $get_kids_sql $filterQryForCriteria;
  8844. //        if ($request->request->has('productIds'))
  8845. //
  8846. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  8847. //        else if ($request->request->has('productCode'))
  8848. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  8849. //        else if ($filterQryForCriteria!='')
  8850. //            $get_kids_sql = $filterQryForCriteria;
  8851. //
  8852. //        else
  8853. //               $get_kids_sql = "select * from inv_products where (product_code  like '%" . $queryStr . "%' or `name`   like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
  8854.         $stmt $em->getConnection()->prepare($get_kids_sql);
  8855.         $stmt->execute();
  8856.         $get_kids $stmt->fetchAll();
  8857.         $productId 0;
  8858.         if (!empty($get_kids)) {
  8859.             foreach ($get_kids as $product) {
  8860.                 $pa = array();
  8861.                 $pa['id'] = $product['format_id'];
  8862.                 $pa['name'] = $product['name'];
  8863.                 $pa['format_code'] = $product['format_code'] . '. ' $product['name'];
  8864.                 $pa['id_code_name'] = $product['format_id'] . '. ' $product['format_code'] . ' - ' $product['name'] . ' ';
  8865.                 $pa['text'] = $product['name'];
  8866.                 $pa['value'] = $product['format_id'];
  8867.                 $data[] = $pa;
  8868.                 $data_by_id[$product['format_id']] = $pa;
  8869.                 $productId $product['format_id'];
  8870.             }
  8871.         }
  8872. //        if($request->query->has('returnJson'))
  8873.         {
  8874.             return new JsonResponse(
  8875.                 array(
  8876.                     'success' => true,
  8877. //                    'page_title' => 'Product Details',
  8878. //                    'company_data' => $company_data,
  8879.                     'data' => $data,
  8880.                     'dataById' => $data_by_id,
  8881.                     'productId' => $productId,
  8882.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8883. //                    'exId'=>$id,
  8884. //                'productByCodeData' => $productByCodeData,
  8885. //                'productData' => $productData,
  8886. //                'currInvList' => $currInvList,
  8887. //                'productList' => Inventory::ProductList($em, $companyId),
  8888. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  8889. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  8890. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  8891. //                'unitList' => Inventory::UnitTypeList($em),
  8892. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  8893. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  8894. //                'warehouseList' => Inventory::WarehouseList($em),
  8895.                 )
  8896.             );
  8897.         }
  8898.     }
  8899.     public
  8900.     function CategoryListSelectAjaxAction(Request $request$queryStr '')
  8901.     {
  8902.         $em $this->getDoctrine()->getManager();
  8903.         $companyId $this->getLoggedUserCompanyId($request);
  8904.         $company_data Company::getCompanyData($em$companyId);
  8905.         $data = [];
  8906.         $data_by_id = [];
  8907.         $html '';
  8908.         $productByCodeData = [];
  8909.         if ($queryStr == '_EMPTY_')
  8910.             $queryStr '';
  8911.         if ($request->request->has('query') && $queryStr == '')
  8912.             $queryStr $request->request->get('queryStr');
  8913.         if ($queryStr == '_EMPTY_')
  8914.             $queryStr '';
  8915.         $filterQryForCriteria "select * from inv_product_categories where company_id=" $companyId " ";
  8916.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  8917.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  8918.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  8919.         if ($filterQryForCriteria != '')
  8920.             $filterQryForCriteria .= "  limit 25";
  8921.         $get_kids_sql $filterQryForCriteria;
  8922. //        if ($request->request->has('productIds'))
  8923. //
  8924. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  8925. //        else if ($request->request->has('productCode'))
  8926. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  8927. //        else if ($filterQryForCriteria!='')
  8928. //            $get_kids_sql = $filterQryForCriteria;
  8929. //
  8930. //        else
  8931. //               $get_kids_sql = "select * from inv_products where (product_code  like '%" . $queryStr . "%' or `name`   like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
  8932.         $stmt $em->getConnection()->prepare($get_kids_sql);
  8933.         $stmt->execute();
  8934.         $get_kids $stmt->fetchAll();
  8935.         $productId 0;
  8936.         if (!empty($get_kids)) {
  8937.             foreach ($get_kids as $product) {
  8938.                 $pa = array();
  8939.                 $pa['id'] = $product['id'];
  8940.                 $pa['name'] = $product['name'];
  8941.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  8942.                 $pa['globalId'] = $product['global_id'];
  8943.                 $pa['text'] = $product['name'];
  8944.                 $pa['value'] = $product['id'];
  8945.                 $pa['igId'] = $product['ig_id'];
  8946. //                $pa['categoryId'] = $product['category_id'];
  8947. //                $pa['subCategoryId'] = $product['sub_category_id'];
  8948.                 $data[] = $pa;
  8949.                 $data_by_id[$product['id']] = $pa;
  8950.                 $productId $product['id'];
  8951.             }
  8952.         }
  8953. //        if($request->query->has('returnJson'))
  8954.         {
  8955.             return new JsonResponse(
  8956.                 array(
  8957.                     'success' => true,
  8958. //                    'page_title' => 'Product Details',
  8959. //                    'company_data' => $company_data,
  8960.                     'data' => $data,
  8961.                     'dataById' => $data_by_id,
  8962.                     'productId' => $productId,
  8963.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  8964. //                    'exId'=>$id,
  8965. //                'productByCodeData' => $productByCodeData,
  8966. //                'productData' => $productData,
  8967. //                'currInvList' => $currInvList,
  8968. //                'productList' => Inventory::ProductList($em, $companyId),
  8969. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  8970. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  8971. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  8972. //                'unitList' => Inventory::UnitTypeList($em),
  8973. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  8974. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  8975. //                'warehouseList' => Inventory::WarehouseList($em),
  8976.                 )
  8977.             );
  8978.         }
  8979.     }
  8980.     public
  8981.     function SubCategoryListSelectAjaxAction(Request $request$queryStr '')
  8982.     {
  8983.         $em $this->getDoctrine()->getManager();
  8984.         $companyId $this->getLoggedUserCompanyId($request);
  8985.         $company_data Company::getCompanyData($em$companyId);
  8986.         $data = [];
  8987.         $data_by_id = [];
  8988.         $html '';
  8989.         $productByCodeData = [];
  8990.         if ($queryStr == '_EMPTY_')
  8991.             $queryStr '';
  8992.         if ($request->request->has('query') && $queryStr == '')
  8993.             $queryStr $request->request->get('queryStr');
  8994.         if ($queryStr == '_EMPTY_')
  8995.             $queryStr '';
  8996.         $filterQryForCriteria "select * from inv_product_sub_categories where company_id=" $companyId " ";
  8997.         if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
  8998.             $filterQryForCriteria .= " and sub_category_id=" $request->request->get('subCategoryId');
  8999.         if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
  9000.             $filterQryForCriteria .= " and category_id=" $request->request->get('categoryId');
  9001.         if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
  9002.             $filterQryForCriteria .= " and ig_id=" $request->request->get('igId');
  9003.         if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
  9004.             if ($request->request->get('parentId') != 0)
  9005.                 $filterQryForCriteria .= " and  parent_id=" $request->request->get('parentId');
  9006.             else
  9007.                 $filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
  9008.         if ($request->request->has('level') && $request->request->get('level') != '')
  9009.             if ($request->request->get('level') != 0)
  9010.                 $filterQryForCriteria .= " and level=" $request->request->get('level');
  9011.             else
  9012.                 $filterQryForCriteria .= " and ( level =0 or level is null) ";
  9013.         $filterQryForCriteria .= " and  ( `name`   like '%" $queryStr "%' ) ";
  9014.         if ($filterQryForCriteria != '')
  9015.             $filterQryForCriteria .= "  limit 25";
  9016.         $get_kids_sql $filterQryForCriteria;
  9017. //        if ($request->request->has('productIds'))
  9018. //
  9019. //           $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
  9020. //        else if ($request->request->has('productCode'))
  9021. //            $get_kids_sql = "select * from inv_products where product_code  like '%" . $request->request->get('productCode') . "%'  and company_id=" . $companyId . " limit 1";
  9022. //        else if ($filterQryForCriteria!='')
  9023. //            $get_kids_sql = $filterQryForCriteria;
  9024. //
  9025. //        else
  9026. //               $get_kids_sql = "select * from inv_products where (product_code  like '%" . $queryStr . "%' or `name`   like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
  9027.         $stmt $em->getConnection()->prepare($get_kids_sql);
  9028.         $stmt->execute();
  9029.         $get_kids $stmt->fetchAll();
  9030.         $productId 0;
  9031.         if (!empty($get_kids)) {
  9032.             foreach ($get_kids as $product) {
  9033.                 $pa = array();
  9034.                 $pa['id'] = $product['id'];
  9035.                 $pa['name'] = $product['name'];
  9036.                 $pa['name_with_id'] = '#' $product['id'] . '. ' $product['name'];
  9037.                 $pa['globalId'] = $product['global_id'];
  9038.                 $pa['parentId'] = $product['parent_id'];
  9039.                 $pa['text'] = $product['name'];
  9040.                 $pa['value'] = $product['id'];
  9041.                 $pa['igId'] = $product['ig_id'];
  9042.                 $pa['categoryId'] = $product['category_id'];
  9043. //                $pa['subCategoryId'] = $product['sub_category_id'];
  9044.                 $data[] = $pa;
  9045.                 $data_by_id[$product['id']] = $pa;
  9046.                 $productId $product['id'];
  9047.             }
  9048.         }
  9049. //        if($request->query->has('returnJson'))
  9050.         {
  9051.             return new JsonResponse(
  9052.                 array(
  9053.                     'success' => true,
  9054. //                    'page_title' => 'Product Details',
  9055. //                    'company_data' => $company_data,
  9056.                     'data' => $data,
  9057.                     'dataById' => $data_by_id,
  9058.                     'productId' => $productId,
  9059.                     'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
  9060. //                    'exId'=>$id,
  9061. //                'productByCodeData' => $productByCodeData,
  9062. //                'productData' => $productData,
  9063. //                'currInvList' => $currInvList,
  9064. //                'productList' => Inventory::ProductList($em, $companyId),
  9065. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9066. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9067. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9068. //                'unitList' => Inventory::UnitTypeList($em),
  9069. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9070. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9071. //                'warehouseList' => Inventory::WarehouseList($em),
  9072.                 )
  9073.             );
  9074.         }
  9075.     }
  9076.     public
  9077.     function ProductByCodeViewAction(Request $request$id 0)
  9078.     {
  9079.         $em $this->getDoctrine()->getManager();
  9080.         $companyId $this->getLoggedUserCompanyId($request);
  9081.         $company_data Company::getCompanyData($em$companyId);
  9082.         $data = [];
  9083.         $html '';
  9084.         $productByCodeData = [];
  9085.         if ($id != 0) {
  9086.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9087.                 ->findOneBy(
  9088.                     array(
  9089.                         'productByCodeId' => $id
  9090.                     )
  9091.                 );
  9092.         } else {
  9093.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9094.                 ->findOneBy(
  9095.                     array(
  9096. //                        'productByCodeId' => $id,
  9097.                         'CompanyId' => $companyId
  9098.                     ), array(
  9099.                         'productByCodeId' => 'DESC'
  9100.                     )
  9101.                 );
  9102.             if ($productByCodeData)
  9103.                 $id $productByCodeData->getProductByCodeId();
  9104.         }
  9105.         if ($id != 0) {
  9106.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9107.                 ->findOneBy(
  9108.                     array(
  9109.                         'id' => $productByCodeData->getProductId()
  9110.                     )
  9111.                 );
  9112.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9113.                 ->findBy(
  9114.                     array(
  9115.                         'productId' => $id
  9116.                     )
  9117.                 );
  9118.             $html $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_snippet.html.twig',
  9119.                 array(
  9120.                     'page_title' => 'Product Details',
  9121.                     'company_data' => $company_data,
  9122.                     'productByCodeData' => $productByCodeData,
  9123.                     'productData' => $productData,
  9124.                     'currInvList' => $currInvList,
  9125.                     'exId' => $id,
  9126.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9127.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9128.                     'productList' => Inventory::ProductList($em$companyId),
  9129.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9130.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9131.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9132.                     'unitList' => Inventory::UnitTypeList($em),
  9133.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9134.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9135.                     'warehouseList' => Inventory::WarehouseList($em),
  9136.                 )
  9137.             );
  9138.         } else {
  9139.             $html $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_snippet.html.twig',
  9140.                 array(
  9141.                     'exId' => $id,
  9142.                 )
  9143.             );
  9144.         }
  9145.         if ($request->query->has('returnJson')) {
  9146.             return new JsonResponse(
  9147.                 array(
  9148.                     'success' => true,
  9149.                     'page_title' => 'Product Details',
  9150.                     'company_data' => $company_data,
  9151.                     'renderedHtml' => $html,
  9152.                     'exId' => $id,
  9153. //                'productByCodeData' => $productByCodeData,
  9154. //                'productData' => $productData,
  9155. //                'currInvList' => $currInvList,
  9156. //                'productList' => Inventory::ProductList($em, $companyId),
  9157. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9158. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9159. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9160. //                'unitList' => Inventory::UnitTypeList($em),
  9161. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9162. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9163. //                'warehouseList' => Inventory::WarehouseList($em),
  9164.                 )
  9165.             );
  9166.         } else {
  9167. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9168. //                ->findBy(
  9169. //                    array(
  9170. ////                        'productByCodeId' => $id,
  9171. //                    'CompanyId'=>$companyId
  9172. //                    )
  9173. //                );
  9174.             $productByCodeList = []; //called by ajax
  9175.             return $this->render('ApplicationBundle:pages/inventory/view:product_by_code_view.html.twig',
  9176.                 array(
  9177.                     'page_title' => 'Product Details',
  9178.                     'company_data' => $company_data,
  9179.                     'renderedHtml' => $html,
  9180.                     'exId' => $id,
  9181.                     'productByCodeList' => $productByCodeList,
  9182. //                'productByCodeData' => $productByCodeData,
  9183. //                'productData' => $productData,
  9184. //                'currInvList' => $currInvList,
  9185. //                'productList' => Inventory::ProductList($em, $companyId),
  9186. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9187. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9188. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9189. //                'unitList' => Inventory::UnitTypeList($em),
  9190. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9191. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9192. //                'warehouseList' => Inventory::WarehouseList($em),
  9193.                 )
  9194.             );
  9195.         }
  9196.     }
  9197.     public
  9198.     function ConsumptionSettingsAction(Request $request$id)
  9199.     {
  9200.         $cc_id '';
  9201.         $cc_name '';
  9202.         $em $this->getDoctrine()->getManager();
  9203.         $companyId $this->getLoggedUserCompanyId($request);
  9204.         $consumptionTypeId 0;
  9205.         if ($request->isMethod('POST')) {
  9206.             $new_cc = [];
  9207.             if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
  9208.                 $em $this->getDoctrine()->getManager();
  9209.                 $new_cc $this->getDoctrine()
  9210.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9211.                     ->findOneBy(
  9212.                         array(
  9213.                             'consumptionTypeId' => $request->request->get('consumptionTypeId'),
  9214.                         )
  9215.                     );
  9216.                 $new_cc->setName($request->request->get('name'));
  9217.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9218.                 $new_cc->setCompanyId($companyId);
  9219.                 $em->flush();
  9220.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9221.                 $this->addFlash(
  9222.                     'success',
  9223.                     'Consumption Information Updated'
  9224.                 );
  9225.             } else {
  9226.                 $new_cc = new ConsumptionType();
  9227.                 $new_cc->setName($request->request->get('name'));
  9228.                 $new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
  9229.                 $new_cc->setCompanyId($companyId);
  9230.                 $em->persist($new_cc);
  9231.                 $em->flush();
  9232.                 $consumptionTypeId $new_cc->getConsumptionTypeId();
  9233.                 $em->flush();
  9234.                 $this->addFlash(
  9235.                     'success',
  9236.                     'New Consumption Type Added'
  9237.                 );
  9238.             }
  9239.         }
  9240.         $extData = [];
  9241.         if ($id != 0) {
  9242.             $extData $this->getDoctrine()
  9243.                 ->getRepository('ApplicationBundle:ConsumptionType')
  9244.                 ->findOneBy(
  9245.                     array(
  9246.                         'consumptionTypeId' => $id
  9247.                     )
  9248.                 );
  9249. //            $cc_data_list = [];
  9250. //            foreach ($cc_data as $value) {
  9251. //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9252. //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9253. //
  9254. //                if ($value->getSupplierCategoryId() == $id) {
  9255. //                    $cc_id = $value->getSupplierCategoryId();
  9256. //                    $cc_name = $value->getName();
  9257. //                }
  9258. //            }
  9259.         }
  9260.         return $this->render('ApplicationBundle:pages/inventory/input_forms:consumption_settings.html.twig',
  9261.             array(
  9262.                 'page_title' => 'Consumption Settings',
  9263.                 'consumptionTypeList' => $this->getDoctrine()
  9264.                     ->getRepository('ApplicationBundle:ConsumptionType')
  9265.                     ->findBy(
  9266.                         array(
  9267.                             'CompanyId' => $companyId
  9268.                         )
  9269.                     ),
  9270.                 'extData' => $extData,
  9271.                 'headList' => Accounts::getParentLedgerHeads($em),
  9272. //                'countryList'=>SalesOrderM::Co
  9273.             )
  9274.         );
  9275.     }
  9276.     public
  9277.     function ProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9278.     {
  9279.         $em $this->getDoctrine()->getManager();
  9280.         $companyId $this->getLoggedUserCompanyId($request);
  9281.         $company_data Company::getCompanyData($em$companyId);
  9282.         $data = [];
  9283.         $html '';
  9284.         $productByCodeData = [];
  9285.         $productDataWeightPackageGm '';
  9286.         $productDataWeightVarianceValue 0;
  9287.         $productDataWeightVarianceType 0;
  9288.         $productByCodeDataObj = [];
  9289.         $dr_id 0;//for dr_id
  9290.         $skipRenderData 0;
  9291.         if ($request->query->has('skipRenderData'))
  9292.             $skipRenderData $request->query->get('skipRenderData');
  9293.         if ($id != 0) {
  9294.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9295.                 ->findOneBy(
  9296.                     array(
  9297.                         'productByCodeId' => $id
  9298.                     )
  9299.                 );
  9300.         } else {
  9301.             if ($request->query->has('scanCode')) {
  9302.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9303.                     ->createQueryBuilder('p');
  9304.                 if ($request->query->has('assigned')) {
  9305.                     $query->where('p.assigned > :av')
  9306.                         ->setParameter('av'$request->query->get('assigned'));
  9307.                 } else
  9308.                     $query->where("1=0");
  9309.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9310.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9311.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9312.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9313.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9314.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9315.                 $query->setMaxResults(1);
  9316.                 $results $query->getQuery()->getResult();
  9317.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9318.             } else
  9319.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9320.                     ->findOneBy(
  9321.                         array(
  9322. //                        'productByCodeId' => $id,
  9323.                             'CompanyId' => $companyId
  9324.                         ), array(
  9325.                             'productByCodeId' => 'DESC'
  9326.                         )
  9327.                     );
  9328.             if ($productByCodeData)
  9329.                 $id $productByCodeData->getProductByCodeId();
  9330.         }
  9331.         if ($id != 0) {
  9332.             $productByCodeDataObj = array(
  9333.                 'salesCode' => $productByCodeData->getSalesCode(),
  9334.                 'sales_code' => $productByCodeData->getSalesCode(),
  9335.                 'sn' => $productByCodeData->getSerialNo(),
  9336.                 'serialNo' => $productByCodeData->getSerialNo(),
  9337.                 'imei1' => $productByCodeData->getImei1(),
  9338.                 'imei2' => $productByCodeData->getImei2(),
  9339.                 'soId' => $productByCodeData->getSalesOrderId(),
  9340.                 'poId' => $productByCodeData->getPurchaseOrderId(),
  9341.                 'irrId' => $productByCodeData->getIrrId(),
  9342.                 'productId' => $productByCodeData->getProductId(),
  9343.                 'productByCodeId' => $productByCodeData->getProductByCodeId(),
  9344.                 'warehouseId' => $productByCodeData->getWarehouseId(),
  9345.                 'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
  9346.                 'stId' => $productByCodeData->getStockTransferId(),
  9347.                 'srId' => $productByCodeData->getStockReceivedNoteId(),
  9348.                 'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
  9349.                 'clientId' => $productByCodeData->getClientId(),
  9350.                 'supplierId' => $productByCodeData->getSupplierId(),
  9351.                 'drId' => $productByCodeData->getDeliveryReceiptId(),
  9352.                 'consumerName' => $productByCodeData->getConsumerName(),
  9353.                 'drItemData' => [],
  9354. //                'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
  9355.             );
  9356.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9357.                 ->findOneBy(
  9358.                     array(
  9359.                         'id' => $productByCodeData->getProductId()
  9360.                     )
  9361.                 );
  9362.             if ($productByCodeData->getProductionId() != null) {
  9363.                 $productionDataHere $em->getRepository('ApplicationBundle:Production')
  9364.                     ->findOneBy(
  9365.                         array(
  9366.                             'productionId' => $productByCodeData->getProductionId()
  9367.                         )
  9368.                     );
  9369.                 if ($productionDataHere) {
  9370.                     $productDataWeightPackageGm $productionDataHere->getPackageWeight();
  9371.                     $productDataWeightVarianceValue $productionDataHere->getPackageWeightVarianceValue();
  9372.                     $productDataWeightVarianceType $productionDataHere->getPackageWeightVarianceType();
  9373.                 }
  9374.             } else {
  9375.                 if ($productData) {
  9376.                     $productDataWeightPackageGm $productData->getWeight();
  9377.                     $productDataWeightVarianceValue $productData->getWeightVarianceValue();
  9378.                     $productDataWeightVarianceType $productData->getWeightVarianceType();
  9379.                 }
  9380.             }
  9381.             if ($productData) {
  9382.                 $productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
  9383.                 $productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
  9384.                 $productByCodeDataObj['productFdm'] = $productData->getProductFdm();
  9385.                 $productByCodeDataObj['productName'] = $productData->getName();
  9386.                 if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
  9387.                     $QD $this->getDoctrine()
  9388.                         ->getRepository('ApplicationBundle:DeliveryReceiptItem')
  9389.                         ->findOneBy(
  9390.                             array(
  9391.                                 'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
  9392.                                 'productId' => $productByCodeData->getProductId(),
  9393.                             )
  9394.                         );
  9395. //            if($request->request->get('wareHouseId')!='')
  9396.                     if ($QD) {
  9397.                         $new_pid $QD->getProductId();
  9398.                         $sales_code_range = [];
  9399.                         if (version_compare(PHP_VERSION'5.4.0''>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE 4)) {
  9400.                             $sales_code_range json_decode($QD->getSalesCodeRange(), true512JSON_BIGINT_AS_STRING);
  9401.                         } else {
  9402.                             $max_int_length strlen((string)PHP_INT_MAX) - 1;
  9403.                             $json_without_bigints preg_replace('/:\s*(-?\d{' $max_int_length ',})/'': "$1"'$QD->getSalesCodeRange());
  9404.                             $sales_code_range json_decode($json_without_bigintstrue);
  9405.                         }
  9406.                         $p_data = array(
  9407.                             'details_id' => $QD->getId(),
  9408.                             'productId' => $new_pid,
  9409.                             'dr_id' => $productByCodeData->getDeliveryReceiptId(),
  9410.                             'product_name' => $productData->getName(),
  9411.                             'qty' => $QD->getQty(),
  9412.                             'delivered' => $QD->getDelivered(),
  9413.                             'unitTypeId' => $QD->getUnitTypeId(),
  9414.                             'deliverable' => $QD->getDeliverable(),
  9415.                             'balance' => $QD->getBalance(),
  9416.                             'salesCodeRangeStr' => $QD->getSalesCodeRange(),
  9417.                             'salesCodeRange' => $sales_code_range,
  9418.                             'sales_codes' => $sales_code_range,
  9419.                             'sales_price' => $QD->getPrice(),
  9420.                             'purchase_price' => $QD->getCurrentPurchasePrice()
  9421. //                        'delivered'=>$product->getDelivered(),
  9422.                         );
  9423.                         $productByCodeDataObj['drItemData'][] = $p_data;
  9424.                     }
  9425.                 }
  9426.             }
  9427.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9428.                 ->findBy(
  9429.                     array(
  9430.                         'productId' => $id
  9431.                     )
  9432.                 );
  9433.             $html = ($skipRenderData == '' $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_for_print_check_snippet.html.twig',
  9434.                 array(
  9435.                     'page_title' => 'Details',
  9436.                     'company_data' => $company_data,
  9437.                     'productByCodeData' => $productByCodeData,
  9438.                     'productByCodeDataObj' => $productByCodeDataObj,
  9439.                     'productData' => $productData,
  9440.                     'currInvList' => $currInvList,
  9441.                     'productDataWeightPackageGm' => $productDataWeightPackageGm,
  9442.                     'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
  9443.                     'productDataWeightVarianceType' => $productDataWeightVarianceType,
  9444.                     'exId' => $id,
  9445.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9446.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9447.                     'productList' => Inventory::ProductList($em$companyId),
  9448.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9449.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9450.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9451.                     'unitList' => Inventory::UnitTypeList($em),
  9452.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9453.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9454.                     'warehouseList' => Inventory::WarehouseList($em),
  9455.                 )
  9456.             ));
  9457.         } else {
  9458.             $html = ($skipRenderData == '' $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_for_print_check_snippet.html.twig',
  9459.                 array(
  9460.                     'exId' => $id,
  9461.                 )
  9462.             ));
  9463.         }
  9464.         if ($request->query->has('returnJson')) {
  9465.             return new JsonResponse(
  9466.                 array(
  9467.                     'success' => true,
  9468.                     'page_title' => 'Product Details',
  9469.                     'company_data' => $company_data,
  9470.                     'renderedHtml' => $html,
  9471.                     'exId' => $id,
  9472.                     'productByCodeDataObj' => $productByCodeDataObj,
  9473. //                'productData' => $productData,
  9474. //                'currInvList' => $currInvList,
  9475. //                'productList' => Inventory::ProductList($em, $companyId),
  9476. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9477. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9478. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9479. //                'unitList' => Inventory::UnitTypeList($em),
  9480. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9481. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9482. //                'warehouseList' => Inventory::WarehouseList($em),
  9483.                 )
  9484.             );
  9485.         } else {
  9486. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9487. //                ->findBy(
  9488. //                    array(
  9489. ////                        'productByCodeId' => $id,
  9490. //                    'CompanyId'=>$companyId
  9491. //                    )
  9492. //                );
  9493.             $productByCodeList = []; //called by ajax
  9494.             return $this->render('ApplicationBundle:pages/inventory/view:product_by_code_assign_check_print.html.twig',
  9495.                 array(
  9496.                     'page_title' => 'Serial Manager',
  9497.                     'company_data' => $company_data,
  9498.                     'renderedHtml' => $html,
  9499.                     'exId' => $id,
  9500.                     'productByCodeList' => $productByCodeList,
  9501.                     'productByCodeDataObj' => $productByCodeDataObj,
  9502. //                'productByCodeData' => $productByCodeData,
  9503. //                'productData' => $productData,
  9504. //                'currInvList' => $currInvList,
  9505. //                'productList' => Inventory::ProductList($em, $companyId),
  9506. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9507. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9508. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9509. //                'unitList' => Inventory::UnitTypeList($em),
  9510. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9511. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9512. //                'warehouseList' => Inventory::WarehouseList($em),
  9513.                 )
  9514.             );
  9515.         }
  9516.     }
  9517.     public
  9518.     function TestProductByCodeCheckAssignPrintAction(Request $request$id 0)
  9519.     {
  9520.         $em $this->getDoctrine()->getManager();
  9521.         $companyId $this->getLoggedUserCompanyId($request);
  9522.         $company_data Company::getCompanyData($em$companyId);
  9523.         $data = [];
  9524.         $html '';
  9525.         $productByCodeData = [];
  9526.         $productByCodeDataObj = [];
  9527.         if ($id != 0) {
  9528.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9529.                 ->findOneBy(
  9530.                     array(
  9531.                         'productByCodeId' => $id
  9532.                     )
  9533.                 );
  9534.         } else {
  9535.             if ($request->query->has('scanCode')) {
  9536.                 $query $em->getRepository('ApplicationBundle:ProductByCode')
  9537.                     ->createQueryBuilder('p');
  9538.                 if ($request->query->has('assigned')) {
  9539.                     $query->where('p.assigned > :av')
  9540.                         ->setParameter('av'$request->query->get('assigned'));
  9541.                 } else
  9542.                     $query->where("1=0");
  9543.                 $query->orWhere("p.salesCode LIKE '%" $request->query->get('scanCode') . "%' ");
  9544.                 $query->orWhere("p.serialNo LIKE '%" $request->query->get('scanCode') . "%' ");
  9545.                 $query->orWhere("p.imei1 LIKE '%" $request->query->get('scanCode') . "%' ");
  9546.                 $query->orWhere("p.imei2 LIKE '%" $request->query->get('scanCode') . "%' ");
  9547.                 $query->orWhere("p.imei3 LIKE '%" $request->query->get('scanCode') . "%' ");
  9548.                 $query->orWhere("p.imei4 LIKE '%" $request->query->get('scanCode') . "%' ");
  9549.                 $query->setMaxResults(1);
  9550.                 $results $query->getQuery()->getResult();
  9551.                 $productByCodeData = isset($results[0]) ? $results[0] : null;
  9552.             } else
  9553.                 $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  9554.                     ->findOneBy(
  9555.                         array(
  9556. //                        'productByCodeId' => $id,
  9557.                             'CompanyId' => $companyId
  9558.                         ), array(
  9559.                             'productByCodeId' => 'DESC'
  9560.                         )
  9561.                     );
  9562.             if ($productByCodeData)
  9563.                 $id $productByCodeData->getProductByCodeId();
  9564.         }
  9565.         if ($id != 0) {
  9566.             $productByCodeDataObj = array(
  9567.                 'sn' => $productByCodeData->getSalesCode(),
  9568.                 'imei1' => $productByCodeData->getImei1(),
  9569.                 'imei2' => $productByCodeData->getImei2(),
  9570.                 'colorId' => $productByCodeData->getColorId(),
  9571.             );
  9572.             $productData $em->getRepository('ApplicationBundle:InvProducts')
  9573.                 ->findOneBy(
  9574.                     array(
  9575.                         'id' => $productByCodeData->getProductId()
  9576.                     )
  9577.                 );
  9578.             $currInvList $em->getRepository('ApplicationBundle:InventoryStorage')
  9579.                 ->findBy(
  9580.                     array(
  9581.                         'productId' => $id
  9582.                     )
  9583.                 );
  9584.             $html $this->renderView('ApplicationBundle:pages/inventory/view:test_product_by_code_for_print_check_snippet.html.twig',
  9585.                 array(
  9586.                     'page_title' => 'Details',
  9587.                     'company_data' => $company_data,
  9588.                     'productByCodeData' => $productByCodeData,
  9589.                     'productData' => $productData,
  9590.                     'currInvList' => $currInvList,
  9591.                     'exId' => $id,
  9592.                     'clientList' => Client::GetExistingClientList($em$companyId),
  9593.                     'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  9594.                     'productList' => Inventory::ProductList($em$companyId),
  9595.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9596.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9597.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9598.                     'unitList' => Inventory::UnitTypeList($em),
  9599.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9600.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9601.                     'warehouseList' => Inventory::WarehouseList($em),
  9602.                 )
  9603.             );
  9604.         } else {
  9605.             $html $this->renderView('ApplicationBundle:pages/inventory/view:test_product_by_code_for_print_check_snippet.html.twig',
  9606.                 array(
  9607.                     'exId' => $id,
  9608.                 )
  9609.             );
  9610.         }
  9611.         if ($request->query->has('returnJson')) {
  9612.             return new JsonResponse(
  9613.                 array(
  9614.                     'success' => true,
  9615.                     'page_title' => 'Product Details',
  9616.                     'company_data' => $company_data,
  9617.                     'renderedHtml' => $html,
  9618.                     'exId' => $id,
  9619.                     'productByCodeDataObj' => $productByCodeDataObj,
  9620. //                'productData' => $productData,
  9621. //                'currInvList' => $currInvList,
  9622. //                'productList' => Inventory::ProductList($em, $companyId),
  9623. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9624. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9625. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9626. //                'unitList' => Inventory::UnitTypeList($em),
  9627. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9628. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9629. //                'warehouseList' => Inventory::WarehouseList($em),
  9630.                 )
  9631.             );
  9632.         } else {
  9633. //            $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
  9634. //                ->findBy(
  9635. //                    array(
  9636. ////                        'productByCodeId' => $id,
  9637. //                    'CompanyId'=>$companyId
  9638. //                    )
  9639. //                );
  9640.             $productByCodeList = []; //called by ajax
  9641.             return $this->render('ApplicationBundle:pages/inventory/view:test_product_by_code_assign_check_print.html.twig',
  9642.                 array(
  9643.                     'page_title' => ' Test Serial Manager',
  9644.                     'company_data' => $company_data,
  9645.                     'renderedHtml' => $html,
  9646.                     'exId' => $id,
  9647.                     'productByCodeList' => $productByCodeList,
  9648.                     'productByCodeDataObj' => $productByCodeDataObj,
  9649. //                'productByCodeData' => $productByCodeData,
  9650. //                'productData' => $productData,
  9651. //                'currInvList' => $currInvList,
  9652. //                'productList' => Inventory::ProductList($em, $companyId),
  9653. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9654. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9655. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9656. //                'unitList' => Inventory::UnitTypeList($em),
  9657. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9658. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9659. //                'warehouseList' => Inventory::WarehouseList($em),
  9660.                 )
  9661.             );
  9662.         }
  9663.     }
  9664.     public
  9665.     function DeleteProductAction(Request $request$id '')
  9666.     {
  9667.         $em $this->getDoctrine()->getManager();
  9668.         $idListArray = [];
  9669.         if ($request->isMethod('POST')) {
  9670.             if ($id == 0)
  9671.                 $id $request->request->get('productId');
  9672.             //now check the product closing , if nothing then we cna remove it
  9673.             $query_here $this->getDoctrine()
  9674.                 ->getRepository('ApplicationBundle:InvClosingBalance')
  9675.                 ->findBy(
  9676.                     array(
  9677.                         'productId' => $request->request->get('productId')
  9678.                     )
  9679.                 );
  9680.             if (!empty($query_here)) {
  9681.                 return new JsonResponse(
  9682.                     array(
  9683.                         'success' => false,
  9684.                     )
  9685.                 );
  9686.             } else {
  9687.                 $qry $em->getRepository('ApplicationBundle:ProductByCode')->findBy(array(
  9688.                     'productId' => $id
  9689.                 ));
  9690.                 foreach ($qry as $det) {
  9691.                     //remove any barcoded products
  9692.                     $em->remove($det);
  9693.                     $em->flush();
  9694.                 }
  9695.                 $qry $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  9696.                     'id' => $id
  9697.                 ));
  9698.                 foreach ($qry as $det) {
  9699.                     //remove any barcoded products
  9700.                     $em->remove($det);
  9701.                     $em->flush();
  9702.                 }
  9703.                 $qry $em->getRepository('ApplicationBundle:InvItemTransaction')->findBy(array(
  9704.                     'productId' => $id
  9705.                 ));
  9706.                 foreach ($qry as $det) {
  9707.                     //remove any barcoded products
  9708.                     $em->remove($det);
  9709.                     $em->flush();
  9710.                 }
  9711.                 return new JsonResponse(
  9712.                     array(
  9713.                         'success' => true,
  9714.                     )
  9715.                 );
  9716.             }
  9717.         }
  9718.         return new JsonResponse(
  9719.             array(
  9720.                 'success' => false,
  9721.             )
  9722.         );
  9723.     }
  9724.     public
  9725.     function RegisterProductAction(Request $request$idListStr '')
  9726.     {
  9727.         $em $this->getDoctrine()->getManager();
  9728.         $companyId $this->getLoggedUserCompanyId($request);
  9729.         $company_data Company::getCompanyData($em$companyId);
  9730.         $session $request->getSession();
  9731. //        System::setSessionForUser($session );
  9732.         $idListArray = [];
  9733.         if ($idListStr != '')
  9734.             $idListArray explode(','$idListStr);
  9735.         $data = [];
  9736. //        if ($request->isMethod('POST')) {
  9737. //            $post = $request->request;
  9738. //            if ($request->request->get('formatId') != '') {
  9739. //                $query_here = $this->getDoctrine()
  9740. //                    ->getRepository('ApplicationBundle:CheckFormat')
  9741. //                    ->findOneBy(
  9742. //                        array(
  9743. //                            'formatId' => $request->request->get('formatId')
  9744. //                        )
  9745. //                    );
  9746. //                if (!empty($query_here))
  9747. //                    $new = $query_here;
  9748. //            } else
  9749. //                $new = new CheckFormat();
  9750. //            $new->setName($request->request->get('name'));
  9751. //            $new->setWidth($request->request->get('width'));
  9752. //            $new->setHeight($request->request->get('height'));
  9753. //            $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
  9754. //            $new->setCheckPayToTop($request->request->get('checkPayToTop'));
  9755. //            $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
  9756. //            $new->setCheckAmountTop($request->request->get('checkAmountTop'));
  9757. //            $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
  9758. //            $new->setCheckAiWTop($request->request->get('checkAiWTop'));
  9759. //            $new->setCheckDateLeft($request->request->get('checkDateLeft'));
  9760. //            $new->setCheckDateTop($request->request->get('checkDateTop'));
  9761. //            $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
  9762. //            $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
  9763. //            $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
  9764. //            $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
  9765. //            $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
  9766. //            $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
  9767. //            $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
  9768. //            $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
  9769. //            $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
  9770. //            $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
  9771. //            $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
  9772. //            $new->setCheckImage($request->request->get('checkImage'));
  9773. //
  9774. //            $em = $this->getDoctrine()->getManager();
  9775. //            $em->persist($new);
  9776. //            $em->flush();
  9777. //
  9778. //        }
  9779. //        if (!empty($idListArray)) {
  9780. //            $query_here = $this->getDoctrine()
  9781. //                ->getRepository('ApplicationBundle:ProductByCode')
  9782. //                ->findBy(
  9783. //                    array(
  9784. //                        'productByCodeId' => $idListArray
  9785. //                    )
  9786. //                );
  9787. //            if (!empty($query_here))
  9788. //                $data = $query_here;
  9789. //
  9790. //        }
  9791. //        else if ($request->query->has('formatId')) {
  9792. //            $query_here = $this->getDoctrine()
  9793. //                ->getRepository('ApplicationBundle:CheckFormat')
  9794. //                ->findOneBy(
  9795. //                    array(
  9796. //                        'formatId' => $request->query->get('formatId')
  9797. //                    )
  9798. //                );
  9799. //            if (!empty($query_here))
  9800. //                $data = $query_here;
  9801. //        }
  9802.         $data = [];
  9803.         $html '';
  9804.         $productByCodeData = [];
  9805.         if ($request->query->has('returnJson')) {
  9806.             return new JsonResponse(
  9807.                 array(
  9808.                     'success' => true,
  9809.                     'page_title' => 'Product Details',
  9810.                     'company_data' => $company_data,
  9811.                     'renderedHtml' => $html,
  9812.                     'data' => $data,
  9813.                     'idListArray' => $idListArray,
  9814. //                    'exId'=>$id,
  9815. //                'productByCodeData' => $productByCodeData,
  9816. //                'productData' => $productData,
  9817. //                'currInvList' => $currInvList,
  9818. //                'productList' => Inventory::ProductList($em, $companyId),
  9819. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  9820. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  9821. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  9822. //                'unitList' => Inventory::UnitTypeList($em),
  9823. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  9824. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  9825. //                'warehouseList' => Inventory::WarehouseList($em),
  9826.                 )
  9827.             );
  9828.         } else {
  9829.             return $this->render('ApplicationBundle:pages/inventory/input_forms:register_product.html.twig',
  9830.                 array(
  9831.                     'page_title' => 'Register Product',
  9832.                     'company_data' => $company_data,
  9833.                     'renderedHtml' => $html,
  9834. //                    'exIdList'=>$i,
  9835.                     'idListArray' => $idListArray,
  9836.                     'data' => $data,
  9837.                     'productByCodeList' => [],
  9838.                     'productByCodeData' => [],
  9839.                     'productList' => Inventory::ProductList($em$companyId),
  9840.                     'subCategoryList' => Inventory::ProductSubCategoryList($em$companyId),
  9841.                     'categoryList' => Inventory::ProductCategoryList($em$companyId),
  9842.                     'igList' => Inventory::ItemGroupList($em$companyId),
  9843.                     'unitList' => Inventory::UnitTypeList($em),
  9844.                     'brandList' => Inventory::GetBrandList($em$companyId),
  9845.                     'warehouse_action_list' => Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object'),
  9846.                     'warehouseList' => Inventory::WarehouseList($em),
  9847.                 )
  9848.             );
  9849.         }
  9850.     }
  9851.     public
  9852.     function BrandViewAction(Request $request)
  9853.     {
  9854.         return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_return.html.twig',
  9855.             array(
  9856.                 'page_title' => 'Stock Return'
  9857.             )
  9858.         );
  9859.     }
  9860.     public
  9861.     function PrintTableDataAction(Request $request)
  9862.     {
  9863.         $em $this->getDoctrine()->getManager();
  9864.         $company_data Company::getCompanyData($em1);
  9865.         $data = [];
  9866.         $print_title "test";
  9867.         $document_mark = array(
  9868.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  9869.             'copy' => ''
  9870.         );
  9871.         $mis_data = [];
  9872.         $p 1;
  9873.         return $this->render('ApplicationBundle:pages/inventory/print:print_table_data.html.twig',
  9874.             array(
  9875.                 'page_title' => 'Data Report',
  9876.                 'data' => $data,
  9877.                 'page_header' => 'Report',
  9878.                 'print_title' => $print_title,
  9879.                 'document_type' => 'Journal voucher',
  9880.                 'document_mark_image' => $document_mark['original'],
  9881.                 'page_header_sub' => 'Add',
  9882. //                'type_list'=>$type_list,
  9883.                 'mis_data' => $mis_data,
  9884.                 'item_data' => [],
  9885.                 'received' => 2,
  9886.                 'return' => 1,
  9887.                 'total_w_vat' => 1,
  9888.                 'total_vat' => 1,
  9889.                 'total_wo_vat' => 1,
  9890.                 'invoice_id' => 'abcd1234',
  9891.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  9892.                 'created_by' => 'created by',
  9893.                 'created_at' => '',
  9894.                 'red' => 0,
  9895.                 'company_name' => $company_data->getName(),
  9896.                 'company_data' => $company_data,
  9897.                 'company_address' => $company_data->getAddress(),
  9898.                 'company_image' => $company_data->getImage(),
  9899.                 'p' => $p
  9900.             )
  9901.         );
  9902.     }
  9903.     public
  9904.     function ReplacementReportAction(Request $request)
  9905.     {
  9906.         $qry_data = array(
  9907.             'warehouseId' => [0],
  9908.             'igId' => [0],
  9909.             'brandId' => [0],
  9910.             'categoryId' => [0],
  9911.             'actionTagId' => [0],
  9912.         );
  9913.         $em $this->getDoctrine()->getManager();
  9914.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  9915.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  9916.         $data_searched = [];
  9917.         $companyId $this->getLoggedUserCompanyId($request);
  9918.         $company_data Company::getCompanyData($em$companyId);
  9919.         $data = [];
  9920.         $print_title "Inventory Report";
  9921.         $document_mark = array(
  9922.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  9923.             'copy' => ''
  9924.         );
  9925.         $post_data $request->request;
  9926.         $start_date $post_data->has('start_date') ? $post_data->get('start_date') : '';
  9927.         $end_date $post_data->has('end_date') ? $post_data->get('end_date') : '';
  9928.         if ($request->isMethod('POST'))
  9929.             $method 'POST';
  9930.         else
  9931.             $method 'GET';
  9932.         {
  9933. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  9934.             $data_searched Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
  9935.                 $request->request$method,
  9936.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  9937.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  9938.                 return new JsonResponse(
  9939.                     array(
  9940.                         'page_title' => 'Inventory ',
  9941.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  9942.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9943.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  9944.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  9945.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  9946.                         'action_tag' => $warehouse_action_list,
  9947.                         'start_date' => $start_date,
  9948.                         'end_date' => $end_date,
  9949.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  9950.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  9951.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  9952.                         'data_searched' => $data_searched,
  9953.                         'success' => empty($data_searched['query_result']) ? false true
  9954.                     )
  9955.                 );
  9956.             }
  9957.             if ($request->request->get('print_data_enabled') == 1) {
  9958.                 $print_sub_title "";
  9959.                 return $this->render('ApplicationBundle:pages/inventory/print:print_replacement_report.html.twig',
  9960.                     array(
  9961.                         'page_title' => 'Replacement Report',
  9962.                         'page_header' => 'Report',
  9963.                         'print_title' => $print_title,
  9964.                         'document_type' => 'Journal voucher',
  9965.                         'document_mark_image' => $document_mark['original'],
  9966.                         'page_header_sub' => 'Add',
  9967.                         'item_data' => [],
  9968.                         'received' => 2,
  9969.                         'return' => 1,
  9970.                         'total_w_vat' => 1,
  9971.                         'total_vat' => 1,
  9972.                         'total_wo_vat' => 1,
  9973.                         'invoice_id' => 'abcd1234',
  9974.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  9975.                         'created_by' => 'created by',
  9976.                         'created_at' => '',
  9977.                         'red' => 0,
  9978.                         'company_name' => $company_data->getName(),
  9979.                         'company_data' => $company_data,
  9980.                         'company_address' => $company_data->getAddress(),
  9981.                         'company_image' => $company_data->getImage(),
  9982.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  9983.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9984.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  9985.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  9986.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  9987.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  9988.                         'action_tag' => $warehouse_action_list,
  9989.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  9990.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  9991.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  9992.                         'start_date' => $start_date,
  9993.                         'end_date' => $end_date,
  9994.                         'data_searched' => $data_searched
  9995.                     )
  9996.                 );
  9997.             }
  9998.         }
  9999.         return $this->render('ApplicationBundle:pages/inventory/report:replacement_report.html.twig',
  10000.             array(
  10001.                 'page_title' => 'Replacement Report',
  10002.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10003.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10004.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10005.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10006.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10007. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10008.                 'action_tag' => $warehouse_action_list,
  10009.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10010.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10011.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10012.                 'start_date' => $start_date,
  10013.                 'end_date' => $end_date,
  10014.                 'data_searched' => $data_searched,
  10015.                 'success' => empty($data_searched['query_result']) ? false true
  10016.             )
  10017.         );
  10018.     }
  10019.     public
  10020.     function InventoryViewAction(Request $request)
  10021.     {
  10022.         $qry_data = array(
  10023.             'warehouseId' => [0],
  10024.             'igId' => [0],
  10025.             'brandId' => [0],
  10026.             'categoryId' => [0],
  10027.             'actionTagId' => [0],
  10028.         );
  10029.         $em $this->getDoctrine()->getManager();
  10030.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  10031.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10032.         $data_searched = [];
  10033.         $companyId $this->getLoggedUserCompanyId($request);
  10034.         $company_data Company::getCompanyData($em$companyId);
  10035.         $data = [];
  10036.         $print_title "Inventory Report";
  10037.         $document_mark = array(
  10038.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10039.             'copy' => ''
  10040.         );
  10041.         if ($request->isMethod('POST'))
  10042.             $method 'POST';
  10043.         else
  10044.             $method 'GET';
  10045.         {
  10046. //            $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
  10047.             $data_searched Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
  10048.                 $request->request$method,
  10049.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
  10050.             if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10051.                 return new JsonResponse(
  10052.                     array(
  10053.                         'page_title' => 'Inventory ',
  10054.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10055.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10056.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10057.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10058.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10059.                         'action_tag' => $warehouse_action_list,
  10060.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10061.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10062.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10063.                         'data_searched' => $data_searched,
  10064.                         'success' => empty($data_searched['query_result']) ? false true
  10065.                     )
  10066.                 );
  10067.             }
  10068.             if ($request->request->get('print_data_enabled') == 1) {
  10069.                 $print_sub_title "";
  10070.                 return $this->render('ApplicationBundle:pages/inventory/print:print_inventory_data.html.twig',
  10071.                     array(
  10072.                         'page_title' => 'Inventory Report',
  10073.                         'page_header' => 'Report',
  10074.                         'print_title' => $print_title,
  10075.                         'document_type' => 'Journal voucher',
  10076.                         'document_mark_image' => $document_mark['original'],
  10077.                         'page_header_sub' => 'Add',
  10078.                         'item_data' => [],
  10079.                         'received' => 2,
  10080.                         'return' => 1,
  10081.                         'total_w_vat' => 1,
  10082.                         'total_vat' => 1,
  10083.                         'total_wo_vat' => 1,
  10084.                         'invoice_id' => 'abcd1234',
  10085.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10086.                         'created_by' => 'created by',
  10087.                         'created_at' => '',
  10088.                         'red' => 0,
  10089.                         'company_name' => $company_data->getName(),
  10090.                         'company_data' => $company_data,
  10091.                         'company_address' => $company_data->getAddress(),
  10092.                         'company_image' => $company_data->getImage(),
  10093.                         'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10094.                         'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10095.                         'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10096.                         'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10097.                         'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10098.                         'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10099.                         'action_tag' => $warehouse_action_list,
  10100.                         'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10101.                         'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10102.                         'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10103.                         'data_searched' => $data_searched
  10104.                     )
  10105.                 );
  10106.             }
  10107.         }
  10108.         return $this->render('ApplicationBundle:pages/inventory/report:inventory_view.html.twig',
  10109.             array(
  10110.                 'page_title' => 'Inventory',
  10111.                 'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId00'_INVENTORY_VIEW_'),
  10112.                 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  10113.                 'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  10114.                 'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  10115.                 'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10116. //                'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  10117.                 'action_tag' => $warehouse_action_list,
  10118.                 'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  10119.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  10120.                 'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
  10121.                 'data_searched' => $data_searched
  10122.             )
  10123.         );
  10124.     }
  10125.     public
  10126.     function GrnListAction(Request $request)
  10127.     {
  10128.         $q $this->getDoctrine()
  10129.             ->getRepository('ApplicationBundle:Grn')
  10130.             ->findBy(
  10131.                 array(
  10132.                     'status' => GeneralConstant::ACTIVE,
  10133. //                    'approved' =>  GeneralConstant::APPROVED,
  10134.                 )
  10135.             );
  10136.         $stage_list = array(
  10137.             => 'Pending',
  10138.             => 'Pending',
  10139.             => 'Complete',
  10140.             => 'Partial',
  10141.         );
  10142.         $data = [];
  10143.         foreach ($q as $entry) {
  10144.             $data[] = array(
  10145.                 'doc_date' => $entry->getGrnDate(),
  10146.                 'id' => $entry->getGrnId(),
  10147.                 'doc_hash' => $entry->getDocumentHash(),
  10148.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  10149.                 'stage' => $stage_list[$entry->getStage()]
  10150.             );
  10151.         }
  10152.         return $this->render('ApplicationBundle:pages/inventory/view:grn_list.html.twig',
  10153.             array(
  10154.                 'page_title' => 'Grn List',
  10155.                 'data' => $data
  10156.             )
  10157.         );
  10158.     }
  10159.     public
  10160.     function ViewGrnAction(Request $request$id)
  10161.     {
  10162.         $em $this->getDoctrine()->getManager();
  10163.         $dt Inventory::GetGrnDetails($em$id);
  10164.         return $this->render('ApplicationBundle:pages/inventory/view:view_grn.html.twig',
  10165.             array(
  10166.                 'page_title' => 'View',
  10167.                 'data' => $dt,
  10168.                 'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
  10169.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10170.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10171.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10172.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10173.                     $id,
  10174.                     $dt['created_by'],
  10175.                     $dt['edited_by'])
  10176.             )
  10177.         );
  10178.     }
  10179.     public
  10180.     function PrintGrnAction(Request $request$id)
  10181.     {
  10182.         $em $this->getDoctrine()->getManager();
  10183.         $dt Inventory::GetGrnDetails($em$id);
  10184.         $company_data Company::getCompanyData($em1);
  10185.         $document_mark = array(
  10186.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10187.             'copy' => ''
  10188.         );
  10189.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10190.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_received_note.html.twig',
  10191.                 array(
  10192.                     //full array here
  10193.                     'pdf' => true,
  10194.                     'page_title' => 'Grn',
  10195.                     'export' => 'pdf,print',
  10196.                     'data' => $dt,
  10197.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10198.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10199.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10200.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10201.                         $id,
  10202.                         $dt['created_by'],
  10203.                         $dt['edited_by']),
  10204.                     'document_mark_image' => $document_mark['original'],
  10205.                     'company_name' => $company_data->getName(),
  10206.                     'company_data' => $company_data,
  10207.                     'company_address' => $company_data->getAddress(),
  10208.                     'company_image' => $company_data->getImage(),
  10209.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10210.                     'red' => 0
  10211.                 )
  10212.             );
  10213.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10214. //                'orientation' => 'landscape',
  10215. //                'enable-javascript' => true,
  10216. //                'javascript-delay' => 1000,
  10217.                 'no-stop-slow-scripts' => false,
  10218.                 'no-background' => false,
  10219.                 'lowquality' => false,
  10220.                 'encoding' => 'utf-8',
  10221. //            'images' => true,
  10222. //            'cookie' => array(),
  10223.                 'dpi' => 300,
  10224.                 'image-dpi' => 300,
  10225. //                'enable-external-links' => true,
  10226. //                'enable-internal-links' => true
  10227.             ));
  10228.             return new Response(
  10229.                 $pdf_response,
  10230.                 200,
  10231.                 array(
  10232.                     'Content-Type' => 'application/pdf',
  10233.                     'Content-Disposition' => 'attachment; filename="grn.pdf"'
  10234.                 )
  10235.             );
  10236.         }
  10237.         return $this->render('ApplicationBundle:pages/inventory/print:print_received_note.html.twig',
  10238.             array(
  10239.                 'page_title' => 'Grn',
  10240.                 'export' => 'pdf,print',
  10241.                 'data' => $dt,
  10242.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10243.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10244.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10245.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10246.                     $id,
  10247.                     $dt['created_by'],
  10248.                     $dt['edited_by']),
  10249.                 'document_mark_image' => $document_mark['original'],
  10250.                 'company_name' => $company_data->getName(),
  10251.                 'company_data' => $company_data,
  10252.                 'company_address' => $company_data->getAddress(),
  10253.                 'company_image' => $company_data->getImage(),
  10254.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10255.                 'red' => 0
  10256.             )
  10257.         );
  10258.     }
  10259.     public
  10260.     function PrintGrnBarcodeAction(Request $request$id)
  10261.     {
  10262.         $em $this->getDoctrine()->getManager();
  10263.         $dt Inventory::GetGrnDetails($em$id);
  10264.         $company_data Company::getCompanyData($em1);
  10265.         $repeatCount 1;
  10266.         if ($request->query->has('repeatCount'))
  10267.             $repeatCount $request->query->get('repeatCount');
  10268.         $document_mark = array(
  10269.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10270.             'copy' => ''
  10271.         );
  10272.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10273.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_grn_barcodes.html.twig',
  10274.                 array(
  10275.                     //full array here
  10276.                     'pdf' => true,
  10277.                     'page_title' => 'Grn Barcodes',
  10278.                     'export' => 'print',
  10279.                     'data' => $dt,
  10280.                     'repeatCount' => $repeatCount,
  10281.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10282.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10283.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10284.                         array_flip(GeneralConstant::$Entity_list)['Grn'],
  10285.                         $id,
  10286.                         $dt['created_by'],
  10287.                         $dt['edited_by']),
  10288.                     'document_mark_image' => $document_mark['original'],
  10289.                     'company_name' => $company_data->getName(),
  10290.                     'company_data' => $company_data,
  10291.                     'company_address' => $company_data->getAddress(),
  10292.                     'company_image' => $company_data->getImage(),
  10293.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  10294.                     'red' => 0
  10295.                 )
  10296.             );
  10297.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10298. //                'orientation' => 'landscape',
  10299.                 'enable-javascript' => true,
  10300. //                'javascript-delay' => 1000,
  10301.                 'no-stop-slow-scripts' => false,
  10302.                 'no-background' => false,
  10303.                 'lowquality' => false,
  10304.                 'encoding' => 'utf-8',
  10305. //            'images' => true,
  10306. //            'cookie' => array(),
  10307.                 'dpi' => 300,
  10308.                 'image-dpi' => 300,
  10309. //                'enable-external-links' => true,
  10310. //                'enable-internal-links' => true
  10311.             ));
  10312.             return new Response(
  10313.                 $pdf_response,
  10314.                 200,
  10315.                 array(
  10316.                     'Content-Type' => 'application/pdf',
  10317.                     'Content-Disposition' => 'attachment; filename="grn_barcodes.pdf"'
  10318.                 )
  10319.             );
  10320.         }
  10321.         return $this->render('ApplicationBundle:pages/inventory/print:print_grn_barcodes.html.twig',
  10322.             array(
  10323.                 'page_title' => 'Grn barcodes',
  10324. //                'export'=>'pdf,print',
  10325.                 'data' => $dt,
  10326.                 'repeatCount' => $repeatCount,
  10327.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['Grn'],
  10328.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10329.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10330.                     array_flip(GeneralConstant::$Entity_list)['Grn'],
  10331.                     $id,
  10332.                     $dt['created_by'],
  10333.                     $dt['edited_by']),
  10334.                 'document_mark_image' => $document_mark['original'],
  10335.                 'company_name' => $company_data->getName(),
  10336.                 'company_data' => $company_data,
  10337.                 'company_address' => $company_data->getAddress(),
  10338.                 'company_image' => $company_data->getImage(),
  10339.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10340.                 'red' => 0
  10341.             )
  10342.         );
  10343.     }
  10344.     public
  10345.     function GenerateBarcodeAction(Request $request$type$id$item_id)
  10346.     {
  10347.         $em $this->getDoctrine()->getManager();
  10348.         $repeatCount 1;
  10349.         $spec_item_id 0;
  10350.         $skip_ids = [];
  10351.         $clearUnnecessaryOnly 0;
  10352.         if ($request->query->has('skipIds'))
  10353.             $skip_ids $request->query->get('skipIds');
  10354.         if ($request->query->has('clearUnnecessaryOnly'))
  10355.             $clearUnnecessaryOnly $request->query->get('clearUnnecessaryOnly');
  10356.         if ($type == 'srcv') {
  10357.             $doc_data $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
  10358.                 array(
  10359.                     'stockReceivedNoteId' => $id
  10360.                 )
  10361.             );
  10362.             if ($item_id == '_single_') {
  10363.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10364.                     array(
  10365.                         'stockReceivedNoteId' => $id,
  10366. //                        'id' => $item_id
  10367.                     )
  10368.                 );
  10369.             } else {
  10370.                 $doc_item_data $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
  10371.                     array(
  10372.                         'stockReceivedNoteId' => $id,
  10373.                         'id' => $item_id
  10374.                     )
  10375.                 );
  10376.             }
  10377.             $inv_acc_data = [
  10378.                 'fa_amount' => 0,
  10379.                 'tg_amount' => 0,
  10380.             ];
  10381.             $inv_acc_data_by_head = [
  10382.             ];
  10383.             $new_non_delivered_sales_code_range = [];
  10384.             foreach ($doc_item_data as $entry) {
  10385.                 //adding transaction
  10386.                 $sales_code_range_ser = [];
  10387.                 if (in_array($entry->getId(), $skip_ids))
  10388.                     continue;
  10389.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10390.                     ->findOneBy(
  10391.                         array(
  10392.                             'id' => $entry->getProductId()
  10393.                         )
  10394.                     );
  10395.                 $stitem $em->getRepository('ApplicationBundle:StockTransferItem')
  10396.                     ->findOneBy(
  10397.                         array(
  10398.                             'id' => $entry->getStockTransferItemId(),
  10399.                             'productId' => $entry->getProductId()
  10400.                         )
  10401.                     );
  10402.                 if ($product) {
  10403.                     if ($product->getHasSerial() == 1) {
  10404.                         //clear if exists
  10405.                         if ($clearUnnecessaryOnly == 1) {
  10406.                             $get_kids_sql "DELETE FROM product_by_code
  10407.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10408. //                $get_kids_sql .=' ORDER BY name ASC';
  10409.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10410.                             $stmt->execute();
  10411.                             $em->flush();
  10412.                         } else {
  10413.                             $get_kids_sql "DELETE FROM product_by_code
  10414.                                 WHERE product_id=" $entry->getProductId() . " and stock_received_note_id=" $doc_data->getStockReceivedNoteId();
  10415. //                $get_kids_sql .=' ORDER BY name ASC';
  10416.                             $stmt $em->getConnection()->prepare($get_kids_sql);
  10417.                             $stmt->execute();
  10418.                             $em->flush();
  10419.                         }
  10420. //                        $check_here = $stmt->fetchAll();
  10421.                         //now addng product by code
  10422.                         $sales_code_range = [];
  10423.                         if ($doc_data->getType() == || $doc_data->getType() == 4) {
  10424. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10425. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10426.                             $product_action_tag_id $entry->getWarehouseActionId();
  10427.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getQty(),
  10428.                                 $doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10429.                                 $entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), nullnullnullnull$doc_data->getStockReceivedNoteId()
  10430.                             );
  10431.                             $sales_code_range $barcodeData['sales_code_range'];
  10432.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10433.                             $em->flush();
  10434.                         }
  10435. //                        else {
  10436. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10437. //
  10438. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10439. //                            } else {
  10440. //
  10441. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10442. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10443. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10444. //                            }
  10445. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10446. //
  10447. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10448. //                            } else {
  10449. //
  10450. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10451. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10452. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10453. //                            }
  10454. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10455. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10456. //                            $new_non_delivered_sales_code_range = [];
  10457. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10458. //                                if (!(in_array($ndsc, $sales_code_range)))
  10459. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10460. //                            }
  10461. //                            if ($sales_code_range != null) {
  10462. //                                foreach ($sales_code_range as $ind => $dt) {
  10463. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10464. //                                        ->findOneBy(
  10465. //                                            array(
  10466. //                                                'salesCode' => [$dt],
  10467. //                                                'productId' => $entry->getProductId()
  10468. //                                            )
  10469. //                                        );
  10470. //
  10471. //                                    if ($np) {
  10472. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10473. //                                        $np->setProductId($entry->getProductId());
  10474. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10475. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10476. //                                        $np->setPosition(1);//in warehouse
  10477. //                                        $np->setStockReceivedNoteId($id);
  10478. //
  10479. //
  10480. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10481. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10482. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10483. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10484. //                                            'direction' => 'in',
  10485. //                                            'warehouseId' => $entry->getWarehouseId(),
  10486. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10487. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10488. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10489. //                                        );
  10490. //                                        $np->setTransactionHistory(json_encode(
  10491. //                                            $trans_history
  10492. //                                        ));
  10493. //
  10494. //
  10495. //                                        $em->persist($np);
  10496. //                                        $em->flush();
  10497. //                                    }
  10498. //                                }
  10499. //                            }
  10500. //                        }
  10501.                     }
  10502.                 }
  10503.                 //adding transaction
  10504.                 if ($stitem) {
  10505.                     $stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
  10506.                 }
  10507.                 $spec_item_id $entry->getId();
  10508.                 if ($item_id == '_single_') {
  10509.                     break;
  10510.                 }
  10511.             }
  10512.         }
  10513.         if ($type == 'irr') {
  10514.             $doc_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacement')->findOneBy(
  10515.                 array(
  10516.                     'itemReceivedAndReplacementId' => $id
  10517.                 )
  10518.             );
  10519.             if ($item_id == '_single_') {
  10520.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10521.                     array(
  10522.                         'itemReceivedAndReplacementId' => $id,
  10523. //                        'id' => $item_id
  10524.                     )
  10525.                 );
  10526.             } else {
  10527.                 $doc_item_data $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
  10528.                     array(
  10529.                         'itemReceivedAndReplacementId' => $id,
  10530.                         'id' => $item_id
  10531.                     )
  10532.                 );
  10533.             }
  10534.             $inv_acc_data = [
  10535.                 'fa_amount' => 0,
  10536.                 'tg_amount' => 0,
  10537.             ];
  10538.             $inv_acc_data_by_head = [
  10539.             ];
  10540.             $new_non_delivered_sales_code_range = [];
  10541.             foreach ($doc_item_data as $entry) {
  10542.                 //adding transaction
  10543.                 $sales_code_range_ser = [];
  10544.                 if (in_array($entry->getId(), $skip_ids))
  10545.                     continue;
  10546.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10547.                     ->findOneBy(
  10548.                         array(
  10549.                             'id' => $entry->getReceivedProductId()
  10550.                         )
  10551.                     );
  10552.                 if ($product) {
  10553.                     if ($product->getHasSerial() == 1) {
  10554.                         //clear if exists
  10555. //                        if($clearUnnecessaryOnly==1) {
  10556. //                            $get_kids_sql = "DELETE FROM product_by_code
  10557. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10558. ////                $get_kids_sql .=' ORDER BY name ASC';
  10559. //
  10560. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10561. //                            $stmt->execute();
  10562. //                            $em->flush();
  10563. //                        }
  10564. //                        else{
  10565. //                            $get_kids_sql = "DELETE FROM product_by_code
  10566. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10567. ////                $get_kids_sql .=' ORDER BY name ASC';
  10568. //
  10569. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10570. //                            $stmt->execute();
  10571. //                            $em->flush();
  10572. //                        }
  10573. //                        $check_here = $stmt->fetchAll();
  10574.                         //now addng product by code
  10575.                         $sales_code_range = [];
  10576.                         if ($entry->getReceivedQty() > 0) {
  10577. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10578. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10579. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10580.                             $barcodeData Inventory::GenerateBarcode($em$entry->getReceivedProductId(), $entry->getReceivedQty(),
  10581.                                 $doc_data->getItemReceivedAndReplacementDate(), 00$doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
  10582.                                 $entry->getReceivedWarehouseActionId(), nullnullnullnullnullnullnullnull$doc_data->getItemReceivedAndReplacementId()
  10583.                             );
  10584.                             $sales_code_range $barcodeData['sales_code_range'];
  10585.                             $entry->setReceivedCodeRange(json_encode($sales_code_range));
  10586.                             $em->flush();
  10587.                         }
  10588. //                        else {
  10589. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10590. //
  10591. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10592. //                            } else {
  10593. //
  10594. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10595. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10596. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10597. //                            }
  10598. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10599. //
  10600. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10601. //                            } else {
  10602. //
  10603. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10604. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10605. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10606. //                            }
  10607. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10608. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10609. //                            $new_non_delivered_sales_code_range = [];
  10610. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10611. //                                if (!(in_array($ndsc, $sales_code_range)))
  10612. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10613. //                            }
  10614. //                            if ($sales_code_range != null) {
  10615. //                                foreach ($sales_code_range as $ind => $dt) {
  10616. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10617. //                                        ->findOneBy(
  10618. //                                            array(
  10619. //                                                'salesCode' => [$dt],
  10620. //                                                'productId' => $entry->getProductId()
  10621. //                                            )
  10622. //                                        );
  10623. //
  10624. //                                    if ($np) {
  10625. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10626. //                                        $np->setProductId($entry->getProductId());
  10627. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10628. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10629. //                                        $np->setPosition(1);//in warehouse
  10630. //                                        $np->setStockReceivedNoteId($id);
  10631. //
  10632. //
  10633. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10634. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10635. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10636. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10637. //                                            'direction' => 'in',
  10638. //                                            'warehouseId' => $entry->getWarehouseId(),
  10639. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10640. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10641. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10642. //                                        );
  10643. //                                        $np->setTransactionHistory(json_encode(
  10644. //                                            $trans_history
  10645. //                                        ));
  10646. //
  10647. //
  10648. //                                        $em->persist($np);
  10649. //                                        $em->flush();
  10650. //                                    }
  10651. //                                }
  10652. //                            }
  10653. //                        }
  10654.                     }
  10655.                 }
  10656.                 //adding transaction
  10657.                 $spec_item_id $entry->getId();
  10658.                 if ($item_id == '_single_') {
  10659.                     break;
  10660.                 }
  10661.             }
  10662.         }
  10663.         if ($type == 'prdcn') {
  10664.             $doc_data $em->getRepository('ApplicationBundle:Production')->findOneBy(
  10665.                 array(
  10666.                     'productionId' => $id
  10667.                 )
  10668.             );
  10669.             if ($item_id == '_single_') {
  10670.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10671.                     array(
  10672.                         'productionId' => $id,
  10673. //                        'id' => $item_id
  10674.                     )
  10675.                 );
  10676.             } else {
  10677.                 $doc_item_data $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
  10678.                     array(
  10679.                         'productionId' => $id,
  10680.                         'id' => $item_id
  10681.                     )
  10682.                 );
  10683.             }
  10684.             $inv_acc_data = [
  10685.                 'fa_amount' => 0,
  10686.                 'tg_amount' => 0,
  10687.             ];
  10688.             $inv_acc_data_by_head = [
  10689.             ];
  10690.             $new_non_delivered_sales_code_range = [];
  10691.             foreach ($doc_item_data as $entry) {
  10692.                 //adding transaction
  10693.                 $sales_code_range_ser = [];
  10694.                 if (in_array($entry->getId(), $skip_ids))
  10695.                     continue;
  10696.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  10697.                     ->findOneBy(
  10698.                         array(
  10699.                             'id' => $entry->getProductId()
  10700.                         )
  10701.                     );
  10702.                 if ($product) {
  10703.                     if ($product->getHasSerial() == 1) {
  10704.                         //clear if exists
  10705. //                        if($clearUnnecessaryOnly==1) {
  10706. //                            $get_kids_sql = "DELETE FROM product_by_code
  10707. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10708. ////                $get_kids_sql .=' ORDER BY name ASC';
  10709. //
  10710. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10711. //                            $stmt->execute();
  10712. //                            $em->flush();
  10713. //                        }
  10714. //                        else{
  10715. //                            $get_kids_sql = "DELETE FROM product_by_code
  10716. //                                WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
  10717. ////                $get_kids_sql .=' ORDER BY name ASC';
  10718. //
  10719. //                            $stmt = $em->getConnection()->prepare($get_kids_sql);
  10720. //                            $stmt->execute();
  10721. //                            $em->flush();
  10722. //                        }
  10723. //                        $check_here = $stmt->fetchAll();
  10724.                         //now addng product by code
  10725.                         $sales_code_range = [];
  10726.                         if ($entry->getProducedQty() > 0) {
  10727. //                if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
  10728. //                    $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
  10729. //                            $product_action_tag_id = $entry->getWarehouseActionId();
  10730.                             $barcodeData Inventory::GenerateBarcode($em$entry->getProductId(), $entry->getProducedQty(),
  10731.                                 $doc_data->getProductionDate(), 00$doc_data->getCompanyId(), $entry->getWarehouseId(),
  10732.                                 $entry->getProducedItemActionTagId(), nullnullnullnullnullnullnull$doc_data->getProductionId(), null
  10733.                             );
  10734.                             $sales_code_range $barcodeData['sales_code_range'];
  10735.                             $entry->setSalesCodeRange(json_encode($sales_code_range));
  10736.                             $em->flush();
  10737.                         }
  10738. //                        else {
  10739. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10740. //
  10741. //                                $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10742. //                            } else {
  10743. //
  10744. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10745. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
  10746. //                                $sales_code_range = json_decode($json_without_bigints, true);
  10747. //                            }
  10748. //                            if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
  10749. //
  10750. //                                $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
  10751. //                            } else {
  10752. //
  10753. //                                $max_int_length = strlen((string)PHP_INT_MAX) - 1;
  10754. //                                $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
  10755. //                                $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
  10756. //                            }
  10757. ////                    $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
  10758. ////                    $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
  10759. //                            $new_non_delivered_sales_code_range = [];
  10760. //                            foreach ($non_delivered_sales_code_range as $ndsc) {
  10761. //                                if (!(in_array($ndsc, $sales_code_range)))
  10762. //                                    $new_non_delivered_sales_code_range[] = $ndsc;
  10763. //                            }
  10764. //                            if ($sales_code_range != null) {
  10765. //                                foreach ($sales_code_range as $ind => $dt) {
  10766. //                                    $np = $em->getRepository('ApplicationBundle:ProductByCode')
  10767. //                                        ->findOneBy(
  10768. //                                            array(
  10769. //                                                'salesCode' => [$dt],
  10770. //                                                'productId' => $entry->getProductId()
  10771. //                                            )
  10772. //                                        );
  10773. //
  10774. //                                    if ($np) {
  10775. //                                        $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
  10776. //                                        $np->setProductId($entry->getProductId());
  10777. //                                        $np->setWarehouseId($entry->getWarehouseId());
  10778. //                                        $np->setWarehouseActionId($entry->getWarehouseActionId());
  10779. //                                        $np->setPosition(1);//in warehouse
  10780. //                                        $np->setStockReceivedNoteId($id);
  10781. //
  10782. //
  10783. //                                        $np->setLastInDate($doc_data->getStockReceivedNoteDate());
  10784. //                                        $np->setStatus(GeneralConstant::ACTIVE);
  10785. //                                        $trans_history = json_decode($np->getTransactionHistory(), true);
  10786. //                                        $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
  10787. //                                            'direction' => 'in',
  10788. //                                            'warehouseId' => $entry->getWarehouseId(),
  10789. //                                            'warehouseActionId' => $entry->getWarehouseActionId(),
  10790. //                                            'fromWarehouseId' => $stitem->getWarehouseId(),
  10791. //                                            'fromWarehouseActionId' => $stitem->getWarehouseActionId()
  10792. //                                        );
  10793. //                                        $np->setTransactionHistory(json_encode(
  10794. //                                            $trans_history
  10795. //                                        ));
  10796. //
  10797. //
  10798. //                                        $em->persist($np);
  10799. //                                        $em->flush();
  10800. //                                    }
  10801. //                                }
  10802. //                            }
  10803. //                        }
  10804.                     }
  10805.                 }
  10806.                 //adding transaction
  10807.                 $spec_item_id $entry->getId();
  10808.                 if ($item_id == '_single_') {
  10809.                     break;
  10810.                 }
  10811.             }
  10812.         }
  10813.         return new JsonResponse(array(
  10814.             'success' => $spec_item_id != true false,
  10815.             'skipIds' => [],
  10816.             'spec_item_id' => $spec_item_id
  10817.         ));
  10818. //        return $this->render('ApplicationBundle:pages/inventory/print:print_srcv_barcodes.html.twig',
  10819. //            array(
  10820. //                'page_title' => 'Srcv barcodes',
  10821. ////                'export'=>'pdf,print',
  10822. //                'data' => $dt,
  10823. //                'repeatCount' => $repeatCount,
  10824. //                'item_id' => $item_id,
  10825. //                'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  10826. //                    $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  10827. //                'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  10828. //                    array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  10829. //                    $id,
  10830. //                    $dt['created_by'],
  10831. //                    $dt['edited_by']),
  10832. //                'document_mark_image' => $document_mark['original'],
  10833. //                                    'company_name' => $company_data->getName(),
  10834. //                    'company_data'=>$company_data,
  10835. //                'company_address' => $company_data->getAddress(),
  10836. //                'company_image' => $company_data->getImage(),
  10837. //                'invoice_footer' => $company_data->getInvoiceFooter(),
  10838. //                'red' => 0
  10839. //
  10840. //            )
  10841. //        );
  10842.     }
  10843.     public
  10844.     function PrintLabelAction(Request $request$id)
  10845.     {
  10846.         $em $this->getDoctrine()->getManager();
  10847. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  10848.         $repeatCount 1;
  10849.         $assignProductId '';
  10850.         $productByCodeIds = [];
  10851.         $print_selection_type 1;
  10852.         $print_selection_string 1;
  10853.         $assignLabelFormatId 0;
  10854.         $assignColorId 0;
  10855.         $assignProductionScheduleId 0;
  10856.         $warehouseId '';
  10857.         $warehouseActionId '';
  10858.         $toAssignPosition '';
  10859.         $printFlag $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
  10860.         $returnJson $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
  10861.         if ($returnJson == 1)
  10862.             $printFlag 0;
  10863.         $companyId $this->getLoggedUserCompanyId($request);
  10864.         if ($request->query->has('repeatCount'))
  10865.             $repeatCount $request->query->get('repeatCount');
  10866.         if ($request->request->has('print_selection_type'))
  10867.             $print_selection_type $request->request->get('print_selection_type');
  10868.         if ($request->request->has('print_selection_string'))
  10869.             $print_selection_string $request->request->get('print_selection_string');
  10870.         if ($request->request->has('productByCodeIds'))
  10871.             $productByCodeIds json_decode($request->request->get('productByCodeIds'), true);
  10872.         if ($request->request->has('formatId'))
  10873.             $assignLabelFormatId $request->request->get('formatId');
  10874.         if ($printFlag == 0) {
  10875.             if ($request->request->has('productSelector'))
  10876.                 $assignProductId $request->request->get('productSelector');
  10877.             if ($request->request->has('colorId'))
  10878.                 $assignColorId $request->request->get('colorId');
  10879.             if ($request->request->has('productionScheduleId'))
  10880.                 $assignProductionScheduleId $request->request->get('productionScheduleId');
  10881.             if ($request->request->has('warehouseId'))
  10882.                 $warehouseId $request->request->get('warehouseId');
  10883.             if ($request->request->has('warehouseActionId'))
  10884.                 $warehouseActionId $request->request->get('warehouseActionId');
  10885.             if ($request->request->has('position'))
  10886.                 $toAssignPosition $request->request->get('position');
  10887.             if ($assignColorId == '')
  10888.                 $assignColorId 0;
  10889.         }
  10890.         if ($productByCodeIds == null)
  10891.             $productByCodeIds = [];
  10892.         $productByCodeData = [];
  10893.         $productList = [];
  10894.         $productIds = [];
  10895.         if ($print_selection_type == 2) {
  10896.             //range
  10897.             $productByCodeIds Inventory::getIdsFromIdSelectionStr($print_selection_string);
  10898.         }
  10899.         $labelData = [
  10900.             'formatId' => 0
  10901.         ];
  10902.         $formatId 0;
  10903.         if (!empty($productByCodeIds)) {
  10904.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  10905.                 ->findBy(
  10906.                     array(
  10907.                         'productByCodeId' => $productByCodeIds
  10908.                     )
  10909.                 );
  10910.             foreach ($productByCodeData as $d) {
  10911.                 if ($d->getStage() < 10$d->setStage(11);
  10912.                 if ($assignProductId != '') {
  10913.                     $d->setProductId($assignProductId);
  10914.                 }
  10915.                 if ($assignColorId != 0) {
  10916.                     $d->setColorId($assignColorId);
  10917.                 } else {
  10918.                     $productData $em->getRepository('ApplicationBundle:InvProducts')
  10919.                         ->findOneBy(
  10920.                             array(
  10921.                                 'id' => $assignProductId
  10922.                             )
  10923.                         );
  10924.                     if ($productData) {
  10925.                         $d->setColorId($productData->getDefaultColorId());
  10926.                     }
  10927.                 }
  10928.                 if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  10929.                     $d->setDefaultLabelFormatId($assignLabelFormatId);
  10930.                     $d->setDeviceLabelFormatId($assignLabelFormatId);
  10931.                 }
  10932.                 $toAssignPosition != '' $d->setPosition($toAssignPosition) : '';
  10933.                 $warehouseId != '' $d->setWarehouseId($warehouseId) : '';
  10934.                 $warehouseActionId != '' $d->setWarehouseActionId($warehouseActionId) : '';
  10935.                 if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  10936.                     $d->setProductionScheduleId($assignProductionScheduleId);
  10937.                     $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  10938.                         ->findOneBy(
  10939.                             array(
  10940.                                 'productionScheduleId' => $assignProductionScheduleId
  10941.                             )
  10942.                         );
  10943.                     if ($productionSchedule) {
  10944.                         if ($assignLabelFormatId != && $assignLabelFormatId != '') {
  10945.                             //becuase it will assigned at previous lines
  10946.                         } else {
  10947.                             $d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  10948.                             $d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  10949.                         }
  10950.                         $d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  10951.                         $d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  10952.                     }
  10953.                 }
  10954.                 $em->flush();
  10955.                 if ($d->getProductId() != '' || $d->getProductId() != null)
  10956.                     $productIds[] = $d->getProductId();
  10957.                 $formatId $d->getDeviceLabelFormatId();
  10958.             }
  10959.         }
  10960.         $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  10961.             ->findOneBy(
  10962.                 array(
  10963.                     'formatId' => $formatId,
  10964. //                        'CompanyId' => $companyId
  10965.                 )
  10966.             );
  10967.         if ($labelFormatHere) {
  10968.             $formatData json_decode($labelFormatHere->getFormatData(), true);
  10969.             if ($formatData == null$formatData = [];
  10970.             $labelData = array(
  10971.                 'id' => $labelFormatHere->getFormatId(),
  10972.                 'formatId' => $labelFormatHere->getFormatId(),
  10973.                 'labelType' => $labelFormatHere->getLabelType(),
  10974.                 'name' => $labelFormatHere->getName(),
  10975.                 'width' => $labelFormatHere->getWidth(),
  10976.                 'pageWidth' => $labelFormatHere->getPageWidth(),
  10977.                 'height' => $labelFormatHere->getheight(),
  10978.                 'pageHeight' => $labelFormatHere->getPageHeight(),
  10979.                 'formatData' => $formatData,
  10980.             );
  10981.         }
  10982.         $productList Inventory::ProductList($em$this->getLoggedUserCompanyId($request), 10''$productIds);
  10983.         $company_data Company::getCompanyData($em1);
  10984.         $document_mark = array(
  10985.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10986.             'copy' => ''
  10987.         );
  10988.         $dt $productByCodeData;
  10989.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  10990.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_label.html.twig',
  10991.                 array(
  10992.                     //full array here
  10993.                     'pdf' => true,
  10994.                     'page_title' => 'Device Labels',
  10995.                     'export' => 'print',
  10996.                     'repeatCount' => $repeatCount,
  10997.                     'labelData' => $labelData,
  10998.                     'brandList' => Inventory::GetBrandList($em$companyId),
  10999. //                    'item_id' => $item_id,
  11000.                     'data' => $dt,
  11001.                     'productList' => $productList,
  11002.                     'approval_data' => [],
  11003.                     'document_log' => [],
  11004.                     'document_mark_image' => $document_mark['original'],
  11005.                     'company_name' => $company_data->getName(),
  11006.                     'company_data' => $company_data,
  11007.                     'company_address' => $company_data->getAddress(),
  11008.                     'company_image' => $company_data->getImage(),
  11009.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11010.                     'red' => 0
  11011.                 )
  11012.             );
  11013.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11014. //                'orientation' => 'landscape',
  11015.                 'enable-javascript' => true,
  11016. //                'javascript-delay' => 1000,
  11017.                 'no-stop-slow-scripts' => false,
  11018.                 'no-background' => false,
  11019.                 'lowquality' => false,
  11020.                 'encoding' => 'utf-8',
  11021. //            'images' => true,
  11022. //            'cookie' => array(),
  11023.                 'dpi' => 300,
  11024.                 'image-dpi' => 300,
  11025. //                'enable-external-links' => true,
  11026. //                'enable-internal-links' => true
  11027.             ));
  11028.             return new Response(
  11029.                 $pdf_response,
  11030.                 200,
  11031.                 array(
  11032.                     'Content-Type' => 'application/pdf',
  11033.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11034.                 )
  11035.             );
  11036.         }
  11037.         $url $this->generateUrl(
  11038.             'print_label'
  11039.         );
  11040.         if ($returnJson == && $printFlag == 0) {
  11041. //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  11042. //                        array(
  11043. //                            'salesOrderId' => $orderId, ///material
  11044. //
  11045. //                        )
  11046. //                    );
  11047.             return new JsonResponse(array(
  11048.                 'success' => true,
  11049. //                        'documentHash' => $order->getDocumentHash(),
  11050. //                'documentId' => $receiptId,
  11051. //                'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
  11052. //
  11053. //                'viewUrl' => $url . "/" . $receiptId,
  11054.             ));
  11055.         } else return $this->render('ApplicationBundle:pages/inventory/print:print_label.html.twig',
  11056.             array(
  11057.                 'page_title' => 'Product Labels',
  11058. //                'export'=>'pdf,print',
  11059.                 'data' => $dt,
  11060.                 'productList' => $productList,
  11061.                 'repeatCount' => $repeatCount,
  11062. //                'item_id' => $item_id,
  11063.                 'labelData' => $labelData,
  11064.                 'brandList' => Inventory::GetBrandList($em$companyId),
  11065.                 'approval_data' => [],
  11066.                 'document_log' => [],
  11067.                 'document_mark_image' => $document_mark['original'],
  11068.                 'company_name' => $company_data->getName(),
  11069.                 'company_data' => $company_data,
  11070.                 'company_address' => $company_data->getAddress(),
  11071.                 'company_image' => $company_data->getImage(),
  11072.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11073.                 'red' => 0
  11074.             )
  11075.         );
  11076.     }
  11077.     public
  11078.     function PrintCartonLabelAction(Request $request$id)
  11079.     {
  11080.         $em $this->getDoctrine()->getManager();
  11081. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11082.         $repeatCount 1;
  11083.         $assignProductId '';
  11084.         $productByCodeIds = [];
  11085.         $cartonId 0;
  11086.         if ($id != 0)
  11087.             $cartonId $id;
  11088.         $colorText '';
  11089.         $weightText '';
  11090.         if ($request->query->has('repeatCount'))
  11091.             $repeatCount $request->query->get('repeatCount');
  11092.         if ($request->request->has('printCartonId'))
  11093.             $cartonId $request->request->get('printCartonId');
  11094.         if ($request->request->has('printCartonColorText'))
  11095.             $colorText $request->request->get('printCartonColorText');
  11096.         if ($request->request->has('printCartonWeightText'))
  11097.             $weightText $request->request->get('printCartonWeightText');
  11098.         $labelData = [
  11099.             'formatId' => 0
  11100.         ];
  11101.         if ($productByCodeIds == null)
  11102.             $productByCodeIds = [];
  11103.         $productByCodeData = [];
  11104.         $cartonData = [];
  11105.         $product = [];
  11106.         if ($cartonId != 0) {
  11107.             $cartonData $em->getRepository('ApplicationBundle:Carton')
  11108.                 ->findOneBy(
  11109.                     array(
  11110.                         'id' => $cartonId
  11111.                     )
  11112.                 );
  11113.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11114.                 ->findBy(
  11115.                     array(
  11116.                         'cartonId' => $cartonId
  11117.                     )
  11118.                 );
  11119. //            if(!empty($productByCodeData))
  11120. //                $product = $em->getRepository('ApplicationBundle:InvProducts')
  11121. //                ->findOneBy(
  11122. //                    array(
  11123. //                        'id' => $productByCodeData[0]->getProductId()
  11124. //                    )
  11125. //                );
  11126. //            else
  11127.             $product $em->getRepository('ApplicationBundle:InvProducts')
  11128.                 ->findOneBy(
  11129.                     array(
  11130.                         'id' => $cartonData->getProductId()
  11131.                     )
  11132.                 );
  11133.             $formatId $cartonData->getCartonLabelFormatId();
  11134.             $labelFormatHere $em->getRepository('ApplicationBundle:LabelFormat')
  11135.                 ->findOneBy(
  11136.                     array(
  11137.                         'formatId' => $formatId,
  11138. //                        'CompanyId' => $companyId
  11139.                     )
  11140.                 );
  11141.             if ($labelFormatHere) {
  11142.                 $formatData json_decode($labelFormatHere->getFormatData(), true);
  11143.                 if ($formatData == null$formatData = [];
  11144.                 $labelData = array(
  11145.                     'id' => $labelFormatHere->getFormatId(),
  11146.                     'formatId' => $labelFormatHere->getFormatId(),
  11147.                     'labelType' => $labelFormatHere->getLabelType(),
  11148.                     'name' => $labelFormatHere->getName(),
  11149.                     'width' => $labelFormatHere->getWidth(),
  11150.                     'pageWidth' => $labelFormatHere->getPageWidth(),
  11151.                     'height' => $labelFormatHere->getheight(),
  11152.                     'pageHeight' => $labelFormatHere->getPageHeight(),
  11153.                     'formatData' => $formatData,
  11154.                 );
  11155.             }
  11156.         }
  11157.         $company_data Company::getCompanyData($em1);
  11158.         $document_mark = array(
  11159.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11160.             'copy' => ''
  11161.         );
  11162.         $dt $productByCodeData;
  11163.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11164.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_carton_label.html.twig',
  11165.                 array(
  11166.                     //full array here
  11167.                     'pdf' => true,
  11168.                     'page_title' => 'Carton Labels',
  11169.                     'export' => 'print',
  11170.                     'labelData' => $labelData,
  11171.                     'repeatCount' => $repeatCount,
  11172. //                    'item_id' => $item_id,
  11173.                     'data' => $dt,
  11174.                     'cartonData' => $cartonData,
  11175.                     'product' => $product,
  11176.                     'colorText' => $colorText,
  11177.                     'weightText' => $weightText,
  11178.                     'approval_data' => [],
  11179.                     'document_log' => [],
  11180.                     'document_mark_image' => $document_mark['original'],
  11181.                     'company_name' => $company_data->getName(),
  11182.                     'company_data' => $company_data,
  11183.                     'company_address' => $company_data->getAddress(),
  11184.                     'company_image' => $company_data->getImage(),
  11185.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11186.                     'red' => 0
  11187.                 )
  11188.             );
  11189.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11190. //                'orientation' => 'landscape',
  11191.                 'enable-javascript' => true,
  11192. //                'javascript-delay' => 1000,
  11193.                 'no-stop-slow-scripts' => false,
  11194.                 'no-background' => false,
  11195.                 'lowquality' => false,
  11196.                 'encoding' => 'utf-8',
  11197. //            'images' => true,
  11198. //            'cookie' => array(),
  11199.                 'dpi' => 300,
  11200.                 'image-dpi' => 300,
  11201. //                'enable-external-links' => true,
  11202. //                'enable-internal-links' => true
  11203.             ));
  11204.             return new Response(
  11205.                 $pdf_response,
  11206.                 200,
  11207.                 array(
  11208.                     'Content-Type' => 'application/pdf',
  11209.                     'Content-Disposition' => 'attachment; filename="device_labels.pdf"'
  11210.                 )
  11211.             );
  11212.         }
  11213.         if ($request->query->has('previewOnly')) {
  11214.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_carton_label.html.twig',
  11215.                 array(
  11216.                     'page_title' => 'Carton Labels',
  11217. //                'export'=>'pdf,print',
  11218.                     'data' => $dt,
  11219.                     'skip_parameters' => 1,
  11220.                     'labelData' => $labelData,
  11221.                     'cartonData' => $cartonData,
  11222.                     'product' => $product,
  11223.                     'colorText' => $colorText,
  11224.                     'weightText' => $weightText,
  11225.                     'repeatCount' => $repeatCount,
  11226. //                'item_id' => $item_id,
  11227.                     'approval_data' => [],
  11228.                     'document_log' => [],
  11229.                     'document_mark_image' => $document_mark['original'],
  11230.                     'company_name' => $company_data->getName(),
  11231.                     'company_data' => $company_data,
  11232.                     'company_address' => $company_data->getAddress(),
  11233.                     'company_image' => $company_data->getImage(),
  11234.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11235.                     'red' => 0
  11236.                 )
  11237.             );
  11238.             if ($request->query->has('returnJson')) {
  11239.                 return new JsonResponse(
  11240.                     array(
  11241.                         'success' => true,
  11242.                         'page_title' => 'Product Details',
  11243.                         'company_data' => $company_data,
  11244.                         'renderedHtml' => $html,
  11245. //                'productData' => $productData,
  11246. //                'currInvList' => $currInvList,
  11247. //                'productList' => Inventory::ProductList($em, $companyId),
  11248. //                'subCategoryList' => Inventory::ProductSubCategoryList($em, $companyId),
  11249. //                'categoryList' => Inventory::ProductCategoryList($em, $companyId),
  11250. //                'igList' => Inventory::ItemGroupList($em, $companyId),
  11251. //                'unitList' => Inventory::UnitTypeList($em),
  11252. //                'brandList' => Inventory::GetBrandList($em, $companyId),
  11253. //                'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
  11254. //                'warehouseList' => Inventory::WarehouseList($em),
  11255.                     )
  11256.                 );
  11257.             }
  11258.         }
  11259.         return $this->render('ApplicationBundle:pages/inventory/print:print_carton_label.html.twig',
  11260.             array(
  11261.                 'page_title' => 'Carton Labels',
  11262. //                'export'=>'pdf,print',
  11263.                 'data' => $dt,
  11264.                 'cartonData' => $cartonData,
  11265.                 'product' => $product,
  11266. //                'productByCodeData' => $productByCodeData,
  11267.                 'colorText' => $colorText,
  11268.                 'weightText' => $weightText,
  11269.                 'repeatCount' => $repeatCount,
  11270.                 'labelData' => $labelData,
  11271. //                'item_id' => $item_id,
  11272.                 'approval_data' => [],
  11273.                 'document_log' => [],
  11274.                 'document_mark_image' => $document_mark['original'],
  11275.                 'company_name' => $company_data->getName(),
  11276.                 'company_data' => $company_data,
  11277.                 'company_address' => $company_data->getAddress(),
  11278.                 'company_image' => $company_data->getImage(),
  11279.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11280.                 'red' => 0
  11281.             )
  11282.         );
  11283.     }
  11284.     public
  11285.     function AssignInfoToProductByCodeAction(Request $request$id)
  11286.     {
  11287.         $em $this->getDoctrine()->getManager();
  11288.         $companyId $this->getLoggedUserCompanyId($request);
  11289. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11290.         $cartonId '';
  11291.         $passStatus 5;
  11292.         $assignProductId '';
  11293.         $assignProductionId '';
  11294.         $assignProductionScheduleId '';
  11295.         $gbWeightGm '';
  11296.         $dvWeightGm '';
  11297.         $cartonWeightGm '';
  11298.         if ($request->request->has('cartonId'))
  11299.             $cartonId $request->request->get('cartonId');
  11300.         if ($request->request->has('passStatus'))
  11301.             $passStatus $request->request->get('passStatus');
  11302.         if ($request->request->has('productByCodeId'))
  11303.             $id $request->request->get('productByCodeId');
  11304.         if ($request->request->has('productId'))
  11305.             $assignProductId $request->request->get('productId');
  11306.         if ($request->request->has('productionId'))
  11307.             $assignProductionId $request->request->get('productionId');
  11308.         if ($request->request->has('productionScheduleId'))
  11309.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11310.         if ($request->request->has('gbWeightGm'))
  11311.             $gbWeightGm $request->request->get('gbWeightGm');
  11312.         if ($request->request->has('dvWeightGm'))
  11313.             $dvWeightGm $request->request->get('dvWeightGm');
  11314.         if ($request->request->has('cartonWeightGm'))
  11315.             $cartonWeightGm $request->request->get('cartonWeightGm');
  11316.         $cartonAssignedAlready 0;
  11317.         $otherData = array(
  11318.             'currentCartonBalance' => 0,
  11319.             'currentCartonCapacity' => 0,
  11320.             'currentCartonAssigned' => 0,
  11321.             'currentCartonFull' => 0,
  11322.         );
  11323.         if ($id != && $id != '') {
  11324.             $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')
  11325.                 ->findOneBy(
  11326.                     array(
  11327.                         'productByCodeId' => $id
  11328.                     )
  11329.                 );
  11330.             if ($assignProductId != ''$productByCodeData->setProductId($assignProductId);
  11331.             if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
  11332.                 $cartonAssignedAlready 1;
  11333.             else if ($cartonId != ''$productByCodeData->setCartonId($cartonId);
  11334.             if ($dvWeightGm != ''$productByCodeData->setSingleWeightGm($dvWeightGm);
  11335.             if ($gbWeightGm != '') {
  11336.                 $productByCodeData->setPackagedWeightGm($gbWeightGm);
  11337.             }
  11338.             $colorText '_NA_';
  11339.             if ($passStatus != 5$productByCodeData->setStage($passStatus);
  11340.             $productByCodeData->setCompanyId($companyId);
  11341.             if ($assignProductionId != '') {
  11342.                 $productByCodeData->setProductionId($assignProductionId);
  11343.                 $productionData $em->getRepository('ApplicationBundle:Production')
  11344.                     ->findOneBy(
  11345.                         array(
  11346.                             'productionId' => $assignProductionId
  11347.                         )
  11348.                     );
  11349.                 if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
  11350.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11351.                         array(
  11352.                             'productionId' => $assignProductionId,
  11353.                             'productId' => $assignProductId,
  11354.                             'type' => 1,
  11355.                         )
  11356.                     );
  11357.                 else
  11358.                     $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11359.                         array(
  11360.                             'productionId' => $assignProductionId,
  11361. //                            'productId' => $assignProductId,
  11362.                             'type' => 1,
  11363.                         )
  11364.                     );
  11365.                 $assignProductionScheduleId $productionData->getProductionScheduleId();
  11366.                 if ($productionItemData) {
  11367.                     $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11368.                     $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11369.                     $productByCodeData->setPosition(1);//in inventory
  11370.                     $productByCodeData->setSerialAssigned(1);
  11371.                     $productByCodeData->setColorId($productionItemData->getColorId());
  11372.                     $productByCodeData->setColorText($productionItemData->getColorText());
  11373.                     $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11374.                     $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11375.                     if ($passStatus == 1)//passed
  11376.                     {
  11377. //                    $transDate = new \DateTime();
  11378. //                    Inventory::addItemToInventoryCompact($em,
  11379. //                        $productionItemData->getProductId(),
  11380. //                        $productionItemData->getWarehouseId(),
  11381. //                        $productionItemData->getWarehouseId(),
  11382. //                        $productionData->getProducedItemActionTagId(),
  11383. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11384. //                        $transDate,
  11385. //                        1,
  11386. //                        1,
  11387. //                        $entry['valueAdd'],
  11388. //                        $entry['valueSub'],
  11389. //                        $entry['price'],
  11390. //                        $this->getLoggedUserCompanyId($request),
  11391. //                        0,
  11392. //                        $entry['entity'],
  11393. //                        $entry['entityId'],
  11394. //                        $entry['entityDocHash']
  11395. //                    );
  11396.                     }
  11397.                     $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11398.                     if ($transHistory == null)
  11399.                         $transHistory = [];
  11400.                     $transHistory[] = array(
  11401.                         'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11402.                         'direction' => 'in',
  11403.                         'warehouseId' => $productionItemData->getWarehouseId(),
  11404.                         'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11405.                         'fromWarehouseId' => 0,
  11406.                         'fromWarehouseActionId' => //stock of goods
  11407.                     );
  11408.                     $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11409.                 }
  11410.             }
  11411.             if ($assignProductionScheduleId != && $assignProductionScheduleId != '') {
  11412.                 $productByCodeData->setProductionScheduleId($assignProductionScheduleId);
  11413.                 $productionSchedule $em->getRepository('ApplicationBundle:ProductionSchedule')
  11414.                     ->findOneBy(
  11415.                         array(
  11416.                             'productionScheduleId' => $assignProductionScheduleId
  11417.                         )
  11418.                     );
  11419.                 if ($productionSchedule) {
  11420.                     $productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
  11421.                     $productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
  11422.                     $productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
  11423.                     $productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
  11424.                     if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
  11425.                         $productionItemData $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
  11426.                             array(
  11427.                                 'productionScheduleId' => $assignProductionScheduleId,
  11428.                                 'productId' => $productionSchedule->getProducedProductId(),
  11429.                                 'type' => 1,
  11430.                             )
  11431.                         );
  11432. //                        $assignProductionScheduleId=$productionData->getProductionScheduleId();
  11433.                         if ($productionItemData) {
  11434.                             $productByCodeData->setProductionId($productionItemData->getProductionId());
  11435.                             $productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
  11436.                             $productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
  11437.                             $productByCodeData->setPosition(1);//in inventory
  11438.                             $productByCodeData->setSerialAssigned(1);
  11439.                             $productByCodeData->setColorId($productionItemData->getColorId());
  11440.                             $productByCodeData->setColorText($productionItemData->getColorText());
  11441.                             $productByCodeData->setLastInDate($productionItemData->getProductionDate());
  11442.                             $productByCodeData->setStatus(GeneralConstant::ACTIVE);
  11443.                             if ($passStatus == 1)//passed
  11444.                             {
  11445. //                    $transDate = new \DateTime();
  11446. //                    Inventory::addItemToInventoryCompact($em,
  11447. //                        $productionItemData->getProductId(),
  11448. //                        $productionItemData->getWarehouseId(),
  11449. //                        $productionItemData->getWarehouseId(),
  11450. //                        $productionData->getProducedItemActionTagId(),
  11451. //                        $productionData->getProducedItemActionTagId(), //finised goods hobe
  11452. //                        $transDate,
  11453. //                        1,
  11454. //                        1,
  11455. //                        $entry['valueAdd'],
  11456. //                        $entry['valueSub'],
  11457. //                        $entry['price'],
  11458. //                        $this->getLoggedUserCompanyId($request),
  11459. //                        0,
  11460. //                        $entry['entity'],
  11461. //                        $entry['entityId'],
  11462. //                        $entry['entityDocHash']
  11463. //                    );
  11464.                             }
  11465.                             $transHistory json_decode($productByCodeData->getTransactionHistory(), true);
  11466.                             if ($transHistory == null)
  11467.                                 $transHistory = [];
  11468.                             $transHistory[] = array(
  11469.                                 'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
  11470.                                 'direction' => 'in',
  11471.                                 'warehouseId' => $productionItemData->getWarehouseId(),
  11472.                                 'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
  11473.                                 'fromWarehouseId' => 0,
  11474.                                 'fromWarehouseActionId' => //stock of goods
  11475.                             );
  11476.                             $productByCodeData->setTransactionHistory(json_encode($transHistory));
  11477.                         }
  11478.                     }
  11479.                 }
  11480.             }
  11481. //                $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
  11482.             $em->flush();
  11483.             //now adding carton
  11484.         }
  11485.         if ($cartonId != '') {
  11486.             $carton $em->getRepository('ApplicationBundle:Carton')
  11487.                 ->findOneBy(
  11488.                     array(
  11489.                         'id' => $cartonId
  11490.                     )
  11491.                 );
  11492.             if ($cartonWeightGm != ''$carton->setCartonWeightGm($cartonWeightGm);
  11493.             $otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
  11494.             if ($cartonAssignedAlready == 0)
  11495.                 $carton->setCartonAssignedCount(($carton->getCartonAssignedCount()) + 1);
  11496.             $otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
  11497.             $otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
  11498.             if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
  11499.                 $otherData['currentCartonFull'] = 1;
  11500.             $em->flush();
  11501.         }
  11502.         if ($cartonId != '') {
  11503. //                    if($cartonAssignedAlready==1)
  11504. //                    {
  11505.             $productByCodeDataListForThisCarton $em->getRepository('ApplicationBundle:ProductByCode')
  11506.                 ->findBy(
  11507.                     array(
  11508.                         'cartonId' => $cartonId
  11509.                     )
  11510.                 );
  11511.             $carton $em->getRepository('ApplicationBundle:Carton')
  11512.                 ->findOneBy(
  11513.                     array(
  11514.                         'id' => $cartonId
  11515.                     )
  11516.                 );
  11517.             $total_carton_predicted_weight 0;
  11518.             $colorTextList = [];
  11519.             $cartonProductByCodeIds = [];
  11520.             foreach ($productByCodeDataListForThisCarton as $pikamaster) {
  11521.                 if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
  11522.                     $cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
  11523.                 if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
  11524.                     $colorTextList[] = $pikamaster->getColorText();
  11525.                 $total_carton_predicted_weight += ($pikamaster->getPackagedWeightGm());
  11526.                 if ($passStatus != 5)
  11527.                     if ($pikamaster->getStage() < $passStatus)
  11528.                         $pikamaster->setStage($passStatus);
  11529.             }
  11530.             if ($carton)
  11531.                 $carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
  11532.             if ($passStatus != 5)
  11533.                 $carton->setStage($passStatus);
  11534.             $carton->setColors(implode(','$colorTextList));
  11535.             $carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
  11536.             $em->flush();
  11537.         }
  11538.         return new JsonResponse(array(
  11539.             'success' => true,
  11540.             'otherData' => $otherData,
  11541.         ));
  11542.     }
  11543.     public
  11544.     function RefreshCartonListAction(Request $request$id)
  11545.     {
  11546.         $em $this->getDoctrine()->getManager();
  11547. //        $dt = Inventory::GetDrDetails($em, $id, $item_id);
  11548.         $cartonListArray = [];
  11549.         $cartonList = [];
  11550.         $assignableCartonList = [];
  11551.         $assignableCartonListArray = [];
  11552.         $assignable 0;
  11553.         $cartonId '';
  11554.         $passStatus 5;
  11555.         $assignProductId '';
  11556.         $assignProductionId '';
  11557.         $assignProductionScheduleId '';
  11558.         if ($request->request->has('productionId'))
  11559.             $assignProductionId $request->request->get('productionId');
  11560.         if ($request->request->has('productionScheduleId'))
  11561.             $assignProductionScheduleId $request->request->get('productionScheduleId');
  11562.         if ($request->request->has('assignable'))
  11563.             $assignable $request->request->get('assignable');
  11564.         $cartonAssignedAlready 0;
  11565.         $otherData = array(
  11566.             'currentCartonBalance' => 0,
  11567.             'currentCartonCapacity' => 0,
  11568.             'currentCartonAssigned' => 0,
  11569.             'currentCartonFull' => 0,
  11570.         );
  11571.         //1st get all cartons for this production id
  11572.         $cartonList $em->getRepository('ApplicationBundle:Carton')
  11573.             ->findBy(
  11574.                 array(
  11575. //                    'productionId' => $assignProductionId,
  11576.                     'productionScheduleId' => $assignProductionScheduleId
  11577.                 )
  11578.             );
  11579.         $foundAssignable 0;
  11580.         $setId 0;
  11581.         $lastdmySer '';
  11582.         foreach ($cartonList as $carton) {
  11583.             $cartonData = array(
  11584.                 'id' => $carton->getId(),
  11585.                 'name' => $carton->getCartonNumber(),
  11586.                 'colors' => $carton->getColors(),
  11587.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11588.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11589.             );
  11590.             $cartonListArray[] = $cartonData;
  11591.             $cartonList[$cartonData['id']] = $cartonData;
  11592.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11593.                 $foundAssignable 1;
  11594.                 $setId $cartonData['id'];
  11595.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11596.                 $assignableCartonListArray[] = $cartonData;
  11597.             }
  11598.         }
  11599.         if ($assignable == && $foundAssignable == 0) {
  11600. //            $productionData = $em->getRepository('ApplicationBundle:Production')
  11601. //                ->findOneBy(
  11602. //                    array(
  11603. //                        'productionId' => $assignProductionId
  11604. //                    )
  11605. //                );
  11606.             $productionScheduleData $em->getRepository('ApplicationBundle:ProductionSchedule')
  11607.                 ->findOneBy(
  11608.                     array(
  11609.                         'productionScheduleId' => $assignProductionScheduleId
  11610.                     )
  11611.                 );
  11612.             $productId 0;
  11613.             $product = [];
  11614.             $productModel '';
  11615.             if ($productionScheduleData)
  11616.                 $productId $productionScheduleData->getProducedProductId();
  11617. //            $productionItem = $em->getRepository('ApplicationBundle:ProductionEntryItem')
  11618. //                ->findOneBy(
  11619. //                    array(
  11620. //                        'productionId' => $assignProductionId,
  11621. //                        'type' => 1
  11622. //                    )
  11623. //                );
  11624.             if ($productId != 0) {
  11625. //                    $productId = $productionItem->getProductId();
  11626.                 $product $em->getRepository('ApplicationBundle:InvProducts')
  11627.                     ->findOneBy(
  11628.                         array(
  11629.                             'id' => $productId,
  11630.                         )
  11631.                     );
  11632.                 $productModel $product->getModelNo();
  11633.             }
  11634.             $carton = new Carton();
  11635.             $carton_capacity $productionScheduleData->getCartonCapacity();
  11636.             $carton->setProductId($productId);
  11637.             $carton->setProductionId($assignProductionId);
  11638.             $carton->setProductionScheduleId($assignProductionScheduleId);
  11639.             if ($productionScheduleData) {
  11640.                 $carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
  11641.             }
  11642.             $carton->setCartonCapacityCount($carton_capacity == null $carton_capacity);
  11643.             $carton->setCartonAssignedCount(0);
  11644.             $carton->setCompanyId($this->getLoggedUserCompanyId($request));
  11645.             $today = new \DateTime();
  11646.             $dmy $productModel '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' $productionScheduleData->getBatchNumber();
  11647.             $ser 0;
  11648.             $carton->setCartonNumberDmy($dmy);
  11649.             $carton->setCartonNumberLastSer(* (($today->format('h')) . '' . ($today->format('i'))));
  11650.             $carton->setCartonNumber($dmy '-' . ($today->format('h')) . '' . ($today->format('i')));
  11651.             $em->persist($carton);
  11652.             $em->flush();
  11653.             $cartonData = array(
  11654.                 'id' => $carton->getId(),
  11655.                 'name' => $carton->getCartonNumber(),
  11656.                 'colors' => $carton->getColors(),
  11657.                 'cartonCapacityCount' => $carton->getCartonCapacityCount(),
  11658.                 'cartonAssignedCount' => $carton->getCartonAssignedCount(),
  11659.             );
  11660.             $cartonListArray[] = $cartonData;
  11661.             $cartonList[$cartonData['id']] = $cartonData;
  11662.             if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
  11663.                 $foundAssignable 1;
  11664.                 $setId $cartonData['id'];
  11665.                 $assignableCartonList[$cartonData['id']] = $cartonData;
  11666.                 $assignableCartonListArray[] = $cartonData;
  11667.             }
  11668.         }
  11669.         return new JsonResponse(array(
  11670.             'success' => true,
  11671.             'cartonList' => $cartonList,
  11672.             'cartonListArray' => $cartonListArray,
  11673.             'assignableCartonList' => $assignableCartonList,
  11674.             'assignableCartonListArray' => $assignableCartonListArray,
  11675.             'setId' => $setId,
  11676.         ));
  11677.     }
  11678.     public
  11679.     function PrintDrBarcodeAction(Request $request$id$item_id)
  11680.     {
  11681.         $em $this->getDoctrine()->getManager();
  11682.         $dt Inventory::GetDrDetails($em$id$item_id);
  11683.         $repeatCount 1;
  11684.         if ($request->query->has('repeatCount'))
  11685.             $repeatCount $request->query->get('repeatCount');
  11686.         $company_data Company::getCompanyData($em1);
  11687.         $document_mark = array(
  11688.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11689.             'copy' => ''
  11690.         );
  11691.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11692.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_dr_barcodes.html.twig',
  11693.                 array(
  11694.                     //full array here
  11695.                     'pdf' => true,
  11696.                     'page_title' => 'Challan Barcodes',
  11697.                     'export' => 'print',
  11698.                     'repeatCount' => $repeatCount,
  11699.                     'item_id' => $item_id,
  11700.                     'data' => $dt,
  11701.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11702.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11703.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11704.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11705.                         $id,
  11706.                         $dt['created_by'],
  11707.                         $dt['edited_by']),
  11708.                     'document_mark_image' => $document_mark['original'],
  11709.                     'company_name' => $company_data->getName(),
  11710.                     'company_data' => $company_data,
  11711.                     'company_address' => $company_data->getAddress(),
  11712.                     'company_image' => $company_data->getImage(),
  11713.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11714.                     'red' => 0
  11715.                 )
  11716.             );
  11717.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11718. //                'orientation' => 'landscape',
  11719.                 'enable-javascript' => true,
  11720. //                'javascript-delay' => 1000,
  11721.                 'no-stop-slow-scripts' => false,
  11722.                 'no-background' => false,
  11723.                 'lowquality' => false,
  11724.                 'encoding' => 'utf-8',
  11725. //            'images' => true,
  11726. //            'cookie' => array(),
  11727.                 'dpi' => 300,
  11728.                 'image-dpi' => 300,
  11729. //                'enable-external-links' => true,
  11730. //                'enable-internal-links' => true
  11731.             ));
  11732.             return new Response(
  11733.                 $pdf_response,
  11734.                 200,
  11735.                 array(
  11736.                     'Content-Type' => 'application/pdf',
  11737.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  11738.                 )
  11739.             );
  11740.         }
  11741.         return $this->render('ApplicationBundle:pages/inventory/print:print_dr_barcodes.html.twig',
  11742.             array(
  11743.                 'page_title' => 'Challan barcodes',
  11744. //                'export'=>'pdf,print',
  11745.                 'data' => $dt,
  11746.                 'repeatCount' => $repeatCount,
  11747.                 'item_id' => $item_id,
  11748.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11749.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11750.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11751.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  11752.                     $id,
  11753.                     $dt['created_by'],
  11754.                     $dt['edited_by']),
  11755.                 'document_mark_image' => $document_mark['original'],
  11756.                 'company_name' => $company_data->getName(),
  11757.                 'company_data' => $company_data,
  11758.                 'company_address' => $company_data->getAddress(),
  11759.                 'company_image' => $company_data->getImage(),
  11760.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11761.                 'red' => 0
  11762.             )
  11763.         );
  11764.     }
  11765.     public
  11766.     function PrintIrrBarcodeAction(Request $request$id$item_id)
  11767.     {
  11768.         $em $this->getDoctrine()->getManager();
  11769.         $dt Inventory::GetIrrDetails($em$id$item_id);
  11770.         $repeatCount 1;
  11771.         if ($request->query->has('repeatCount'))
  11772.             $repeatCount $request->query->get('repeatCount');
  11773.         $company_data Company::getCompanyData($em1);
  11774.         $document_mark = array(
  11775.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11776.             'copy' => ''
  11777.         );
  11778.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11779.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_irr_barcodes.html.twig',
  11780.                 array(
  11781.                     //full array here
  11782.                     'pdf' => true,
  11783.                     'page_title' => 'Sales Return Barcodes',
  11784.                     'export' => 'print',
  11785.                     'repeatCount' => $repeatCount,
  11786.                     'item_id' => $item_id,
  11787.                     'data' => $dt,
  11788.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11789.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11790.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11791.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11792.                         $id,
  11793.                         $dt['created_by'],
  11794.                         $dt['edited_by']),
  11795.                     'document_mark_image' => $document_mark['original'],
  11796.                     'company_name' => $company_data->getName(),
  11797.                     'company_data' => $company_data,
  11798.                     'company_address' => $company_data->getAddress(),
  11799.                     'company_image' => $company_data->getImage(),
  11800.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11801.                     'red' => 0
  11802.                 )
  11803.             );
  11804.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11805. //                'orientation' => 'landscape',
  11806.                 'enable-javascript' => true,
  11807. //                'javascript-delay' => 1000,
  11808.                 'no-stop-slow-scripts' => false,
  11809.                 'no-background' => false,
  11810.                 'lowquality' => false,
  11811.                 'encoding' => 'utf-8',
  11812. //            'images' => true,
  11813. //            'cookie' => array(),
  11814.                 'dpi' => 300,
  11815.                 'image-dpi' => 300,
  11816. //                'enable-external-links' => true,
  11817. //                'enable-internal-links' => true
  11818.             ));
  11819.             return new Response(
  11820.                 $pdf_response,
  11821.                 200,
  11822.                 array(
  11823.                     'Content-Type' => 'application/pdf',
  11824.                     'Content-Disposition' => 'attachment; filename="irr_barcodes.pdf"'
  11825.                 )
  11826.             );
  11827.         }
  11828.         return $this->render('ApplicationBundle:pages/inventory/print:print_irr_barcodes.html.twig',
  11829.             array(
  11830.                 'page_title' => 'Sales Return barcodes',
  11831. //                'export'=>'pdf,print',
  11832.                 'data' => $dt,
  11833.                 'repeatCount' => $repeatCount,
  11834.                 'item_id' => $item_id,
  11835.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11836.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11837.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11838.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  11839.                     $id,
  11840.                     $dt['created_by'],
  11841.                     $dt['edited_by']),
  11842.                 'document_mark_image' => $document_mark['original'],
  11843.                 'company_name' => $company_data->getName(),
  11844.                 'company_data' => $company_data,
  11845.                 'company_address' => $company_data->getAddress(),
  11846.                 'company_image' => $company_data->getImage(),
  11847.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11848.                 'red' => 0
  11849.             )
  11850.         );
  11851.     }
  11852.     public
  11853.     function PrintSrcvBarcodeAction(Request $request$id$item_id)
  11854.     {
  11855.         $em $this->getDoctrine()->getManager();
  11856.         $dt Inventory::GetSrcvDetails($em$id$item_id);
  11857.         $repeatCount 1;
  11858.         if ($request->query->has('repeatCount'))
  11859.             $repeatCount $request->query->get('repeatCount');
  11860.         $company_data Company::getCompanyData($em1);
  11861.         $document_mark = array(
  11862.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11863.             'copy' => ''
  11864.         );
  11865.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11866.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_srcv_barcodes.html.twig',
  11867.                 array(
  11868.                     //full array here
  11869.                     'pdf' => true,
  11870.                     'page_title' => 'Grn Barcodes',
  11871.                     'export' => 'print',
  11872.                     'repeatCount' => $repeatCount,
  11873.                     'item_id' => $item_id,
  11874.                     'data' => $dt,
  11875.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11876.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11877.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11878.                         array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11879.                         $id,
  11880.                         $dt['created_by'],
  11881.                         $dt['edited_by']),
  11882.                     'document_mark_image' => $document_mark['original'],
  11883.                     'company_name' => $company_data->getName(),
  11884.                     'company_data' => $company_data,
  11885.                     'company_address' => $company_data->getAddress(),
  11886.                     'company_image' => $company_data->getImage(),
  11887.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11888.                     'red' => 0
  11889.                 )
  11890.             );
  11891.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11892. //                'orientation' => 'landscape',
  11893.                 'enable-javascript' => true,
  11894. //                'javascript-delay' => 1000,
  11895.                 'no-stop-slow-scripts' => false,
  11896.                 'no-background' => false,
  11897.                 'lowquality' => false,
  11898.                 'encoding' => 'utf-8',
  11899. //            'images' => true,
  11900. //            'cookie' => array(),
  11901.                 'dpi' => 300,
  11902.                 'image-dpi' => 300,
  11903. //                'enable-external-links' => true,
  11904. //                'enable-internal-links' => true
  11905.             ));
  11906.             return new Response(
  11907.                 $pdf_response,
  11908.                 200,
  11909.                 array(
  11910.                     'Content-Type' => 'application/pdf',
  11911.                     'Content-Disposition' => 'attachment; filename="srcv_barcodes.pdf"'
  11912.                 )
  11913.             );
  11914.         }
  11915.         return $this->render('ApplicationBundle:pages/inventory/print:print_srcv_barcodes.html.twig',
  11916.             array(
  11917.                 'page_title' => 'Srcv barcodes',
  11918. //                'export'=>'pdf,print',
  11919.                 'data' => $dt,
  11920.                 'repeatCount' => $repeatCount,
  11921.                 'item_id' => $item_id,
  11922.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11923.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  11924.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  11925.                     array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
  11926.                     $id,
  11927.                     $dt['created_by'],
  11928.                     $dt['edited_by']),
  11929.                 'document_mark_image' => $document_mark['original'],
  11930.                 'company_name' => $company_data->getName(),
  11931.                 'company_data' => $company_data,
  11932.                 'company_address' => $company_data->getAddress(),
  11933.                 'company_image' => $company_data->getImage(),
  11934.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11935.                 'red' => 0
  11936.             )
  11937.         );
  11938.     }
  11939. //product by code
  11940.     public
  11941.     function ImeiListExcelUploadAction(Request $request)
  11942.     {
  11943.         $lastIndex $request->request->get('lastIndex'0);
  11944.         if ($request->isMethod('POST')) {
  11945.             $post $request->request;
  11946.             if ($request->request->has('chunkData')) {
  11947.                 //now getting the relevant checks
  11948.                 $check_list = [];
  11949.                 $csv_data $request->request->get('chunkData', []);
  11950.                 $em $this->getDoctrine()->getManager();
  11951.                 foreach ($csv_data as $ind => $data_row) {
  11952. //                    if ($ind == 1)
  11953. //                        continue;
  11954.                     $np $this->getDoctrine()
  11955.                         ->getRepository('ApplicationBundle:ProductByCode')
  11956.                         ->findOneBy(
  11957.                             array(
  11958.                                 'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
  11959. //                    'approved' =>  GeneralConstant::APPROVED,
  11960.                             )
  11961.                         );
  11962.                     if (!$np)
  11963.                         $np = new ProductByCode();
  11964. //                    $np = new ProductByCode();
  11965.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  11966.                     if (isset($data_row[1])) $np->setProductId($data_row[1]);
  11967.                     if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
  11968.                     if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
  11969.                     if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
  11970.                     $np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
  11971.                     if (isset($data_row[4])) $np->setImei1($data_row[4]);
  11972.                     if (isset($data_row[5])) $np->setImei2($data_row[5]);
  11973.                     if (isset($data_row[6])) $np->setImei3($data_row[6]);
  11974.                     if (isset($data_row[7])) $np->setImei4($data_row[7]);
  11975.                     if (isset($data_row[8])) $np->setBtMac($data_row[8]);
  11976.                     if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
  11977.                     $np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
  11978.                     $np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
  11979.                     $np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
  11980.                     $np->setPurchaseOrderId(0);
  11981.                     $np->setGrnId(0);
  11982.                     $np->setStage(0);
  11983.                     if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
  11984. //                $np->setSalesCode($data_row[3]);
  11985.                     if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
  11986.                     $np->setSalesCodeSer(0);
  11987.                     $np->setSalesCodeDmy('');
  11988.                     $np->setPurchaseCodeRange("");
  11989.                     $np->setPurchaseReceiptDate(null);
  11990.                     $np->setLastInDate(null);
  11991.                     $np->setStatus(GeneralConstant::ACTIVE);
  11992.                     $np->setTransactionHistory(json_encode([
  11993.                         ]
  11994.                     ));
  11995.                     $np->setPurchaseWarrantyLastDate(null);
  11996.                     $em->persist($np);
  11997.                     $em->flush();
  11998.                 }
  11999.                 return new JsonResponse(array(
  12000.                     "success" => true,
  12001.                     "lastIndex" => $lastIndex,
  12002.                     "file_path" => '',
  12003.                     "csv_data" => $csv_data,
  12004.                     //                "debug_data"=>System::encryptSignature($r)
  12005.                 ));
  12006.             } else {
  12007.                 $path "";
  12008.                 $file_path "";
  12009.                 //            var_dump($request->files);
  12010.                 //        var_dump($request->getFile());
  12011.                 foreach ($request->files as $uploadedFile) {
  12012.                     //            if($uploadedFile->getImage())
  12013.                     //                var_dump($uploadedFile->getFile());
  12014.                     //                var_dump($uploadedFile);
  12015.                     if ($uploadedFile != null) {
  12016.                         $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  12017.                         $path $fileName;
  12018.                         $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  12019.                         if (!file_exists($upl_dir)) {
  12020.                             mkdir($upl_dir0777true);
  12021.                         }
  12022.                         $file $uploadedFile->move($upl_dir$path);
  12023.                     }
  12024.                 }
  12025.                 //        print_r($file);
  12026.                 if ($path != "")
  12027.                     $file_path 'uploads/FileUploads/' $path;
  12028.                 $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  12029.                 //
  12030.                 //            $img_file = file_get_contents($g_path);
  12031.                 //            $r=base64_encode($img_file);
  12032.                 $row 1;
  12033.                 $csv_data = [];
  12034.                 if (($handle fopen($g_path"r")) !== FALSE) {
  12035.                     while (($data fgetcsv($handle1000",")) !== FALSE) {
  12036.                         $num count($data);
  12037.                         $csv_data[$row] = $data;
  12038.                         //                    echo "<p> $num fields in line $row: <br /></p>\n";
  12039.                         $row++;
  12040.                         //                    for ($c=0; $c < $num; $c++) {
  12041.                         //                        echo $data[$c] . "<br />\n";
  12042.                         //                    }
  12043.                     }
  12044.                     fclose($handle);
  12045.                 }
  12046.                 //now getting the relevant checks
  12047.                 $check_list = [];
  12048.                 $em $this->getDoctrine()->getManager();
  12049.                 foreach ($csv_data as $ind => $data_row) {
  12050.                     if ($ind == 1)
  12051.                         continue;
  12052.                     $np = new ProductByCode();
  12053.                     $np->setCompanyId($this->getLoggedUserCompanyId($request));
  12054.                     $np->setProductId($data_row[1]);
  12055.                     $np->setLcNumber($data_row[0]);
  12056.                     $np->setCartonNumber($data_row[2]);
  12057.                     $np->setSerialNo($data_row[3]);
  12058.                     $np->setSerialAssigned(0);
  12059.                     $np->setImei1($data_row[4]);
  12060.                     $np->setImei2($data_row[5]);
  12061.                     $np->setImei3($data_row[6]);
  12062.                     $np->setImei4($data_row[7]);
  12063.                     $np->setBtMac($data_row[8]);
  12064.                     $np->setWlanMac($data_row[9]);
  12065.                     $np->setWarehouseId(0);
  12066.                     $np->setWarehouseActionId(0);
  12067.                     $np->setPosition(0);//in inventory
  12068.                     $np->setPurchaseOrderId(0);
  12069.                     $np->setGrnId(0);
  12070.                     $np->setStage(0);
  12071.                     $np->setSalesCodeRange(json_encode([$data_row[3]]));
  12072. //                $np->setSalesCode($data_row[3]);
  12073.                     $np->setSalesCode($data_row[4]); //IMEI
  12074.                     $np->setSalesCodeSer(0);
  12075.                     $np->setSalesCodeDmy('');
  12076.                     $np->setPurchaseCodeRange("");
  12077.                     $np->setPurchaseReceiptDate(null);
  12078.                     $np->setLastInDate(null);
  12079.                     $np->setStatus(GeneralConstant::ACTIVE);
  12080.                     $np->setTransactionHistory(json_encode([
  12081.                         ]
  12082.                     ));
  12083.                     $np->setPurchaseWarrantyLastDate(null);
  12084.                     $em->persist($np);
  12085.                     $em->flush();
  12086.                 }
  12087.                 return new JsonResponse(array(
  12088.                     "success" => true,
  12089.                     "lastIndex" => $lastIndex,
  12090.                     "file_path" => $file_path,
  12091.                     "csv_data" => $csv_data,
  12092.                     //                "debug_data"=>System::encryptSignature($r)
  12093.                 ));
  12094.             }
  12095.         }
  12096.         return new JsonResponse(array(
  12097.             "success" => false,
  12098.             "file_path" => '',
  12099.             "csv_data" => [],
  12100.             "lastIndex" => $lastIndex,
  12101.         ));
  12102.     }
  12103.     public
  12104.     function ProductByCodeListAction(Request $request)
  12105.     {
  12106.         $em $this->getDoctrine()->getManager();
  12107.         $companyId $this->getLoggedUserCompanyId($request);
  12108.         $listData Inventory::GetProductListForProductByCodeListAjaxAction($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  12109.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  12110.             if ($request->query->has('dataTableQry')) {
  12111.                 return new JsonResponse(
  12112.                     $listData
  12113.                 );
  12114.             }
  12115.         }
  12116.         $q = [];
  12117. //        $q = $this->getDoctrine()
  12118. //            ->getRepository('ApplicationBundle:ProductByCode')
  12119. //            ->findBy(
  12120. //                array(
  12121. //                    'status' => GeneralConstant::ACTIVE,
  12122. ////                    'approved' =>  GeneralConstant::APPROVED,
  12123. //                )
  12124. //
  12125. //            );
  12126.         //temp start
  12127. //        foreach($q as $np) {
  12128. //            if($np->getPosition()==1) {   /// only starting ones or in warehouse ones
  12129. //                $temp_obj = json_decode($np->getTransactionHistory());
  12130. //                if ($temp_obj != null) {
  12131. //                    $transHistory = [];
  12132. //                    $transHistory[] = $temp_obj;
  12133. //                    $np->setTransactionHistory(json_encode($transHistory));
  12134. //                }
  12135. //            }
  12136. //            $em->flush();
  12137. //        }
  12138.         ///temp end
  12139.         $stage_list = array(
  12140.             => 'Pending',
  12141.             => 'Pending',
  12142.             => 'Complete',
  12143.             => 'Partial',
  12144.         );
  12145.         $data = [];
  12146. //        foreach($q as $entry)
  12147. //        {
  12148. //            $data[]=array(
  12149. //                'doc_date'=>$entry->getStockRequisitionDate(),
  12150. //                'id'=>$entry->getStockRequisitionId(),
  12151. //                'doc_hash'=>$entry->getDocumentHash(),
  12152. //                'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
  12153. //                'stage'=>$stage_list[$entry->getStage()]
  12154. //
  12155. //            );
  12156. //        }
  12157.         return $this->render('ApplicationBundle:pages/inventory/view:product_by_code_list.html.twig',
  12158.             array(
  12159.                 'page_title' => 'Product List',
  12160.                 'data' => $q,
  12161. //                'listData' => $listData,
  12162.                 'products' => Inventory::ProductList($em),
  12163.                 'warehouseList' => Inventory::WarehouseList($em)
  12164.             )
  12165.         );
  12166.     }
  12167. //SR
  12168.     public
  12169.     function SrListAction(Request $request)
  12170.     {
  12171.         $q $this->getDoctrine()
  12172.             ->getRepository('ApplicationBundle:StockRequisition')
  12173.             ->findBy(
  12174.                 array(
  12175.                     'status' => GeneralConstant::ACTIVE,
  12176. //                    'approved' =>  GeneralConstant::APPROVED,
  12177.                 )
  12178.                 ,
  12179.                 array(
  12180.                     'stockRequisitionDate' => 'DESC'
  12181.                 )
  12182.             );
  12183.         $stage_list = array(
  12184.             => 'Pending',
  12185.             => 'Pending',
  12186.             => 'Complete',
  12187.             => 'Partial',
  12188.         );
  12189.         $data = [];
  12190.         foreach ($q as $entry) {
  12191.             $data[] = array(
  12192.                 'doc_date' => $entry->getStockRequisitionDate(),
  12193.                 'id' => $entry->getStockRequisitionId(),
  12194.                 'doc_hash' => $entry->getDocumentHash(),
  12195.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12196.                 'stage' => $stage_list[$entry->getStage()],
  12197.                 'indentTagged' => $entry->getIndentTagged(),
  12198.                 'srIds' => $entry->getSrIds(),
  12199.                 'irIds' => $entry->getIrIds(),
  12200.                 'prIds' => $entry->getPrIds(),
  12201.                 'poIds' => $entry->getPoIds(),
  12202.             );
  12203.         }
  12204.         return $this->render('ApplicationBundle:pages/inventory/view:sr_list.html.twig',
  12205.             array(
  12206.                 'page_title' => 'Stock Requisition List',
  12207.                 'data' => $data
  12208.             )
  12209.         );
  12210.     }
  12211.     public
  12212.     function ViewSrAction(Request $request$id)
  12213.     {
  12214.         $em $this->getDoctrine()->getManager();
  12215.         $dt Inventory::GetSrDetails($em$id);
  12216.         return $this->render('ApplicationBundle:pages/inventory/view:view_stock_requisition.html.twig',
  12217.             array(
  12218.                 'page_title' => 'Stock requisition',
  12219.                 'data' => $dt,
  12220.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12221.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12222.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12223.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12224.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12225.                     $id,
  12226.                     $dt['created_by'],
  12227.                     $dt['edited_by'])
  12228.             )
  12229.         );
  12230.     }
  12231.     public
  12232.     function PrintSrAction(Request $request$id)
  12233.     {
  12234.         $em $this->getDoctrine()->getManager();
  12235.         $dt Inventory::GetSrDetails($em$id);
  12236.         $company_data Company::getCompanyData($em1);
  12237.         $document_mark = array(
  12238.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12239.             'copy' => ''
  12240.         );
  12241.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12242.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_sr.html.twig',
  12243.                 array(
  12244.                     //full array here
  12245.                     'pdf' => true,
  12246.                     'page_title' => 'Stock REquisition',
  12247.                     'export' => 'pdf,print',
  12248.                     'data' => $dt,
  12249.                     'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12250.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12251.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12252.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12253.                         array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12254.                         $id,
  12255.                         $dt['created_by'],
  12256.                         $dt['edited_by']),
  12257.                     'document_mark_image' => $document_mark['original'],
  12258.                     'company_name' => $company_data->getName(),
  12259.                     'company_data' => $company_data,
  12260.                     'company_address' => $company_data->getAddress(),
  12261.                     'company_image' => $company_data->getImage(),
  12262.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12263.                     'red' => 0
  12264.                 )
  12265.             );
  12266.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12267. //                'orientation' => 'landscape',
  12268. //                'enable-javascript' => true,
  12269. //                'javascript-delay' => 1000,
  12270.                 'no-stop-slow-scripts' => false,
  12271.                 'no-background' => false,
  12272.                 'lowquality' => false,
  12273.                 'encoding' => 'utf-8',
  12274. //            'images' => true,
  12275. //            'cookie' => array(),
  12276.                 'dpi' => 300,
  12277.                 'image-dpi' => 300,
  12278. //                'enable-external-links' => true,
  12279. //                'enable-internal-links' => true
  12280.             ));
  12281.             return new Response(
  12282.                 $pdf_response,
  12283.                 200,
  12284.                 array(
  12285.                     'Content-Type' => 'application/pdf',
  12286.                     'Content-Disposition' => 'attachment; filename="stock_requisition_' $id '.pdf"'
  12287.                 )
  12288.             );
  12289.         }
  12290.         return $this->render('ApplicationBundle:pages/inventory/print:print_sr.html.twig',
  12291.             array(
  12292.                 'page_title' => 'Stock Requisition',
  12293.                 'export' => 'pdf,print',
  12294.                 'data' => $dt,
  12295.                 'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
  12296.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12297.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12298.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12299.                     array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
  12300.                     $id,
  12301.                     $dt['created_by'],
  12302.                     $dt['edited_by']),
  12303.                 'document_mark_image' => $document_mark['original'],
  12304.                 'company_name' => $company_data->getName(),
  12305.                 'company_data' => $company_data,
  12306.                 'company_address' => $company_data->getAddress(),
  12307.                 'company_image' => $company_data->getImage(),
  12308.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12309.                 'red' => 0
  12310.             )
  12311.         );
  12312.     }
  12313. //IR
  12314.     public
  12315.     function IrListAction(Request $request)
  12316.     {
  12317.         $q $this->getDoctrine()
  12318.             ->getRepository('ApplicationBundle:StoreRequisition')
  12319.             ->findBy(
  12320.                 array(
  12321.                     'status' => GeneralConstant::ACTIVE,
  12322. //                    'approved' =>  GeneralConstant::APPROVED,
  12323.                 ),
  12324.                 array(
  12325.                     'storeRequisitionDate' => 'DESC'
  12326.                 )
  12327.             );
  12328.         $stage_list = array(
  12329.             => 'Pending',
  12330.             => 'Pending',
  12331.             => 'Complete',
  12332.             => 'Partial',
  12333.         );
  12334.         $data = [];
  12335.         foreach ($q as $entry) {
  12336.             $data[] = array(
  12337.                 'doc_date' => $entry->getStoreRequisitionDate(),
  12338.                 'id' => $entry->getStoreRequisitionId(),
  12339.                 'doc_hash' => $entry->getDocumentHash(),
  12340.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12341.                 'stage' => $stage_list[$entry->getStage()],
  12342.                 'prTagged' => $entry->getIndentTagged(),
  12343.                 'srIds' => $entry->getSrIds(),
  12344.                 'irIds' => $entry->getIrIds(),
  12345.                 'prIds' => $entry->getPrIds(),
  12346.                 'poIds' => $entry->getPoIds(),
  12347.             );
  12348.         }
  12349.         return $this->render('ApplicationBundle:pages/inventory/view:ir_list.html.twig',
  12350.             array(
  12351.                 'page_title' => 'Indent Requisition List',
  12352.                 'data' => $data
  12353.             )
  12354.         );
  12355.     }
  12356.     public
  12357.     function ViewIrAction(Request $request$id)
  12358.     {
  12359.         $em $this->getDoctrine()->getManager();
  12360.         $dt Inventory::GetIrDetails($em$id);
  12361.         return $this->render('ApplicationBundle:pages/inventory/view:view_indent_requisition.html.twig',
  12362.             array(
  12363.                 'page_title' => 'Indent',
  12364.                 'data' => $dt,
  12365.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12366.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12367.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12368.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12369.                     $id,
  12370.                     $dt['created_by'],
  12371.                     $dt['edited_by'])
  12372.             )
  12373.         );
  12374.     }
  12375.     public
  12376.     function PrintIrAction(Request $request$id)
  12377.     {
  12378.         $em $this->getDoctrine()->getManager();
  12379.         $dt Inventory::GetIrDetails($em$id);
  12380.         $company_data Company::getCompanyData($em1);
  12381.         $document_mark = array(
  12382.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12383.             'copy' => ''
  12384.         );
  12385.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12386.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_ir.html.twig',
  12387.                 array(
  12388.                     //full array here
  12389.                     'pdf' => true,
  12390.                     'page_title' => 'Indent Requisition',
  12391.                     'export' => 'pdf,print',
  12392.                     'data' => $dt,
  12393.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12394.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12395.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12396.                         array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12397.                         $id,
  12398.                         $dt['created_by'],
  12399.                         $dt['edited_by']),
  12400.                     'document_mark_image' => $document_mark['original'],
  12401.                     'company_name' => $company_data->getName(),
  12402.                     'company_data' => $company_data,
  12403.                     'company_address' => $company_data->getAddress(),
  12404.                     'company_image' => $company_data->getImage(),
  12405.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12406.                     'red' => 0
  12407.                 )
  12408.             );
  12409.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12410. //                'orientation' => 'landscape',
  12411. //                'enable-javascript' => true,
  12412. //                'javascript-delay' => 1000,
  12413.                 'no-stop-slow-scripts' => false,
  12414.                 'no-background' => false,
  12415.                 'lowquality' => false,
  12416.                 'encoding' => 'utf-8',
  12417. //            'images' => true,
  12418. //            'cookie' => array(),
  12419.                 'dpi' => 300,
  12420.                 'image-dpi' => 300,
  12421. //                'enable-external-links' => true,
  12422. //                'enable-internal-links' => true
  12423.             ));
  12424.             return new Response(
  12425.                 $pdf_response,
  12426.                 200,
  12427.                 array(
  12428.                     'Content-Type' => 'application/pdf',
  12429.                     'Content-Disposition' => 'attachment; filename="indent_' $id '.pdf"'
  12430.                 )
  12431.             );
  12432.         }
  12433.         return $this->render('ApplicationBundle:pages/inventory/print:print_ir.html.twig',
  12434.             array(
  12435.                 'page_title' => 'Indent Requisition',
  12436.                 'export' => 'pdf,print',
  12437.                 'data' => $dt,
  12438.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12439.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12440.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12441.                     array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
  12442.                     $id,
  12443.                     $dt['created_by'],
  12444.                     $dt['edited_by']),
  12445.                 'document_mark_image' => $document_mark['original'],
  12446.                 'company_name' => $company_data->getName(),
  12447.                 'company_data' => $company_data,
  12448.                 'company_address' => $company_data->getAddress(),
  12449.                 'company_image' => $company_data->getImage(),
  12450.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12451.                 'red' => 0
  12452.             )
  12453.         );
  12454.     }
  12455. //PR
  12456.     public
  12457.     function PrListAction(Request $request)
  12458.     {
  12459.         $q $this->getDoctrine()
  12460.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12461.             ->findBy(
  12462.                 array(
  12463.                     'status' => GeneralConstant::ACTIVE,
  12464. //                    'approved' =>  GeneralConstant::APPROVED,
  12465.                 ),
  12466.                 array(
  12467.                     'purchaseRequisitionDate' => 'DESC'
  12468.                 )
  12469.             );
  12470.         $stage_list = array(
  12471.             => 'Pending',
  12472.             => 'Pending',
  12473.             => 'Complete',
  12474.             => 'Partial',
  12475.         );
  12476.         $data = [];
  12477.         foreach ($q as $entry) {
  12478.             $data[] = array(
  12479.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12480.                 'id' => $entry->getPurchaseRequisitionId(),
  12481.                 'doc_hash' => $entry->getDocumentHash(),
  12482.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12483.                 'acquisition_status' => $entry->getAcquisitionStatus(),
  12484.                 'acquisition_start_date' => $entry->getAcquisitionStartDate(),
  12485.                 'acquisition_end_date' => $entry->getAcquisitionEndDate(),
  12486.                 'acquisition_method' => $entry->getquotationAcquisitionMethod(),
  12487.                 'poTagged' => $entry->getPoTagged(),
  12488.                 'typeHash' => $entry->getTypehash(),
  12489.                 'srIds' => $entry->getSrIds(),
  12490.                 'irIds' => $entry->getIrIds(),
  12491.                 'prIds' => $entry->getPrIds(),
  12492.                 'poIds' => $entry->getPoIds(),
  12493.             );
  12494.         }
  12495.         return $this->render('ApplicationBundle:pages/inventory/view:pr_list.html.twig',
  12496.             array(
  12497.                 'page_title' => 'Purchase Requisition List',
  12498.                 'data' => $data
  12499.             )
  12500.         );
  12501.     }
  12502.     public
  12503.     function ServiceRequisitionListAction(Request $request)
  12504.     {
  12505.         $q $this->getDoctrine()
  12506.             ->getRepository('ApplicationBundle:PurchaseRequisition')
  12507.             ->findBy(
  12508.                 array(
  12509.                     'status' => GeneralConstant::ACTIVE,
  12510. //                    'approved' =>  GeneralConstant::APPROVED,
  12511.                 ),
  12512.                 array(
  12513.                     'purchaseRequisitionDate' => 'DESC'
  12514.                 )
  12515.             );
  12516.         $stage_list = array(
  12517.             => 'Pending',
  12518.             => 'Pending',
  12519.             => 'Complete',
  12520.             => 'Partial',
  12521.         );
  12522.         $data = [];
  12523.         foreach ($q as $entry) {
  12524.             $data[] = array(
  12525.                 'doc_date' => $entry->getPurchaseRequisitionDate(),
  12526.                 'id' => $entry->getPurchaseRequisitionId(),
  12527.                 'doc_hash' => $entry->getDocumentHash(),
  12528.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  12529.                 'poTagged' => $entry->getPoTagged(),
  12530.                 'typeHash' => $entry->getTypehash(),
  12531.                 'srIds' => $entry->getSrIds(),
  12532.                 'irIds' => $entry->getIrIds(),
  12533.                 'prIds' => $entry->getPrIds(),
  12534.                 'poIds' => $entry->getPoIds(),
  12535.             );
  12536.         }
  12537.         return $this->render('ApplicationBundle:pages/inventory/view:service_requisition_list.html.twig',
  12538.             array(
  12539.                 'page_title' => 'Service Requisition List',
  12540.                 'data' => $data
  12541.             )
  12542.         );
  12543.     }
  12544.     public
  12545.     function ViewPrAction(Request $request$id)
  12546.     {
  12547.         $em $this->getDoctrine()->getManager();
  12548.         $dt Inventory::GetPrDetails($em$id);
  12549.         $companyId $this->getLoggedUserCompanyId($request);
  12550.         return $this->render('ApplicationBundle:pages/inventory/view:view_purchase_requisition.html.twig',
  12551.             array(
  12552.                 'page_title' => 'Purchase Requisition',
  12553.                 'data' => $dt,
  12554.                 'branchList' => Client::BranchList($em$companyId),
  12555.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12556.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12557.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12558.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12559.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12560.                     $id,
  12561.                     $dt['created_by'],
  12562.                     $dt['edited_by'])
  12563.             )
  12564.         );
  12565.     }
  12566.     public
  12567.     function ViewServiceRequisitionAction(Request $request$id)
  12568.     {
  12569.         $em $this->getDoctrine()->getManager();
  12570.         $dt Inventory::GetPrDetails($em$id);
  12571.         return $this->render('ApplicationBundle:pages/inventory/view:view_purchase_requisition.html.twig',
  12572.             array(
  12573.                 'page_title' => 'Service Requisition',
  12574.                 'data' => $dt,
  12575.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12576.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12577.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12578.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12579.                     $id,
  12580.                     $dt['created_by'],
  12581.                     $dt['edited_by'])
  12582.             )
  12583.         );
  12584.     }
  12585.     public
  12586.     function PrintPrAction(Request $request$id)
  12587.     {
  12588.         $em $this->getDoctrine()->getManager();
  12589.         $dt Inventory::GetPrDetails($em$id);
  12590.         $companyId $this->getLoggedUserCompanyId($request);
  12591.         $company_data Company::getCompanyData($em$companyId);
  12592.         $document_mark = array(
  12593.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  12594.             'copy' => ''
  12595.         );
  12596.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  12597.             $html $this->renderView('ApplicationBundle:pages/inventory/print:print_pr.html.twig',
  12598.                 array(
  12599.                     //full array here
  12600.                     'pdf' => true,
  12601.                     'page_title' => 'Purchase Requisition',
  12602.                     'export' => 'pdf,print',
  12603.                     'data' => $dt,
  12604.                     'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12605.                         $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12606.                     'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12607.                         array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12608.                         $id,
  12609.                         $dt['created_by'],
  12610.                         $dt['edited_by']),
  12611.                     'document_mark_image' => $document_mark['original'],
  12612.                     'branchList' => Client::BranchList($em$companyId),
  12613.                     'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12614.                     'company_name' => $company_data->getName(),
  12615.                     'company_data' => $company_data,
  12616.                     'company_address' => $company_data->getAddress(),
  12617.                     'company_image' => $company_data->getImage(),
  12618.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  12619.                     'red' => 0
  12620.                 )
  12621.             );
  12622.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  12623. //                'orientation' => 'landscape',
  12624. //                'enable-javascript' => true,
  12625. //                'javascript-delay' => 1000,
  12626.                 'no-stop-slow-scripts' => false,
  12627.                 'no-background' => false,
  12628.                 'lowquality' => false,
  12629.                 'encoding' => 'utf-8',
  12630. //            'images' => true,
  12631. //            'cookie' => array(),
  12632.                 'dpi' => 300,
  12633.                 'image-dpi' => 300,
  12634. //                'enable-external-links' => true,
  12635. //                'enable-internal-links' => true
  12636.             ));
  12637.             return new Response(
  12638.                 $pdf_response,
  12639.                 200,
  12640.                 array(
  12641.                     'Content-Type' => 'application/pdf',
  12642.                     'Content-Disposition' => 'attachment; filename="purchase_requisition_' $id '.pdf"'
  12643.                 )
  12644.             );
  12645.         }
  12646.         return $this->render('ApplicationBundle:pages/inventory/print:print_pr.html.twig',
  12647.             array(
  12648.                 'page_title' => 'Purchase Requisition',
  12649.                 'export' => 'pdf,print',
  12650.                 'data' => $dt,
  12651.                 'approval_data' => System::checkIfApprovalExists($emarray_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12652.                     $id$request->getSession()->get(UserConstants::USER_LOGIN_ID)),
  12653.                 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
  12654.                     array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
  12655.                     $id,
  12656.                     $dt['created_by'],
  12657.                     $dt['edited_by']),
  12658.                 'document_mark_image' => $document_mark['original'],
  12659.                 'company_name' => $company_data->getName(),
  12660.                 'company_data' => $company_data,
  12661.                 'branchList' => Client::BranchList($em$companyId),
  12662.                 'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
  12663.                 'company_address' => $company_data->getAddress(),
  12664.                 'company_image' => $company_data->getImage(),
  12665.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  12666.                 'red' => 0
  12667.             )
  12668.         );
  12669.     }
  12670.     public
  12671.     function CreateSecondaryDeliveryReceiptAction(Request $request)
  12672.     {
  12673.         $em $this->getDoctrine()->getManager();
  12674.         $companyId $this->getLoggedUserCompanyId($request);
  12675.         $userBranchIdList $request->getSession()->get('branchIdList');
  12676.         if ($userBranchIdList == null$userBranchIdList = [];
  12677.         $userBranchId $request->getSession()->get('branchId');
  12678.         if ($request->isMethod('POST')) {
  12679.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  12680.             $dochash $request->request->get('docHash'); //change
  12681.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12682.             $approveRole 1;  //created
  12683.             $approveHash $request->request->get('approvalHash');
  12684.             if (!DocValidation::isInsertable($em$entity_id$dochash,
  12685.                 $loginId$approveRole$approveHash)
  12686.             ) {
  12687.                 $this->addFlash(
  12688.                     'error',
  12689.                     'Sorry Couldnot insert Data.'
  12690.                 );
  12691.             } else {
  12692.                 $receiptId SalesOrderM::CreateNewSecondaryDeliveryReceipt($this->getDoctrine()->getManager(), $request->request,
  12693.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  12694.                     $this->getLoggedUserCompanyId($request));
  12695.                 //now add Approval info
  12696.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12697.                 $approveRole 1;  //created
  12698.                 System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12699.                     $receiptId,
  12700.                     $loginId,
  12701.                     $approveRole,
  12702.                     $request->request->get('approvalHash'));
  12703.                 $options = array(
  12704.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  12705.                     'notification_server' => $this->container->getParameter('notification_server'),
  12706.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  12707.                     'url' => $this->generateUrl(
  12708.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]
  12709.                         ['entity_view_route_path_name']
  12710.                     )
  12711.                 );
  12712.                 System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  12713.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  12714.                     $receiptId,
  12715.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  12716.                 );
  12717.                 $this->addFlash(
  12718.                     'success',
  12719.                     'New Delivery Receipt Created'
  12720.                 );
  12721.                 $url $this->generateUrl(
  12722.                     'view_delivery_receipt'
  12723.                 );
  12724.                 return $this->redirect($url "/" $receiptId);
  12725.             }
  12726.         }
  12727.         $debugData = [];
  12728. //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  12729. //            array(
  12730. //                'deliveryReceiptId'=>$dr_id
  12731. //            )
  12732. //        );
  12733.         $new_swld = new \DateTime('2017-07-09');
  12734. //        if ($entry->getWarranty() > 0)
  12735. //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  12736.         $debugData[] = $new_swld->format('Y-m-d');
  12737.         $debugData[] = $new_swld;
  12738. //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  12739.         $debugData[] = '+' '1' ' month';
  12740.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  12741.         $warehouseIds = [];
  12742.         foreach ($branchList as $br) {
  12743.             $warehouseIds[] = $br['warehouseId'];
  12744.         }
  12745.         return $this->render('ApplicationBundle:pages/inventory/input_forms:secondaryDeliveryReceipt.html.twig',
  12746.             array(
  12747.                 'page_title' => 'New Delivery Receipt',
  12748.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  12749.                 'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
  12750.                 'ClientList' => SalesOrderM::GetSecondaryClientList($em),
  12751.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  12752.                 'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em$warehouseIds),
  12753.                 'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em$warehouseIds),
  12754.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  12755.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  12756.                 'debugData' => $debugData,
  12757.             )
  12758.         );
  12759.     }
  12760.     public
  12761.     function AddUnitTypeAction(Request $request$id 0)
  12762.     {
  12763.         $em $this->getDoctrine()->getManager();
  12764.         $companyId $this->getLoggedUserCompanyId($request);
  12765.         if ($request->isMethod('POST')) {
  12766.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  12767.             $unitType = new UnitType();
  12768.             $unitType->setName($request->request->get('name'));
  12769.             $unitType->setStatus(1);
  12770.             $em->persist($unitType);
  12771.             $em->flush();
  12772.             $this->addFlash(
  12773.                 'success',
  12774.                 'Unit Type Added'
  12775.             );
  12776.         }
  12777.         $unitTypeDeatails $em->getRepository(UnitType::class)->findAll();
  12778.         return $this->render('ApplicationBundle:pages/inventory/input_forms:addUnitType.html.twig',
  12779.             array(
  12780.                 'page_title' => 'Add Unit Type',
  12781.                 'unitTypeDeatails' => $unitTypeDeatails
  12782.             )
  12783.         );
  12784.     }
  12785.     public
  12786.     function SubcategoryListAction()
  12787.     {
  12788.         return $this->render('ApplicationBundle:pages/inventory/input_forms:subCategoryList.html.twig',
  12789.             array(
  12790.                 'page_title' => 'Sub Category List',
  12791.             )
  12792.         );
  12793.     }
  12794. }